1.3 gin路由配置

  • 基本路由
    gin 框架中采用的路由库是 httprouter。
    // 创建带有默认中间件的路由:    // 日志与恢复中间件    router := gin.Default()    //创建不带中间件的路由:    //r := gin.New()    router.GET("/someGet", getting)    router.POST("/somePost", posting)    router.PUT("/somePut", putting)    router.DELETE("/someDelete", deleting)    router.PATCH("/somePatch", patching)    router.HEAD("/someHead", head)    router.OPTIONS("/someOptions", options)
  • 路由参数

api 参数通过Context的Param方法来获取

router.GET("/string/:name", func(c *gin.Context) {        name := c.Param("name")        fmt.Println("Hello %s", name)    })

URL 参数通过 DefaultQuery 或 Query 方法获取

// url 为 http://localhost:8080/welcome?name=ningskyer时// 输出 Hello ningskyer// url 为 http://localhost:8080/welcome时// 输出 Hello Guestrouter.GET("/welcome", func(c *gin.Context) {    name := c.DefaultQuery("name", "Guest") //可设置默认值    // 是 c.Request.URL.Query().Get("lastname") 的简写    lastname := c.Query("lastname")     fmt.Println("Hello %s", name)})

表单参数通过 PostForm 方法获取

//formrouter.POST("/form", func(c *gin.Context) {    type := c.DefaultPostForm("type", "alert")//可设置默认值    msg := c.PostForm("msg")    title := c.PostForm("title")    fmt.Println("type is %s, msg is %s, title is %s", type, msg, title)})
  • 路由群组
    someGroup := router.Group("/someGroup")    {        someGroup.GET("/someGet", getting)        someGroup.POST("/somePost", posting)    }

Leave a Reply

Your email address will not be published. Required fields are marked *