Gin

Hello World

import (
"gopkg.in/gin-gonic/gin.v1"
"net/http"
)

func main(){

router := gin.Default() //创建路由

router.GET("/", func(c *gin.Context) { //增加路由
c.String(http.StatusOK, "Hello World")
})
router.Run(":8000") // 8000启动
}

路由

gin的路由来自httprouter库

func main(){
router := gin.Default()

router.GET("/user/:name/*action", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
}

query string

func main(){
router := gin.Default()
router.GET("/welcome", func(c *gin.Context) {
firstname := c.DefaultQuery("firstname", "Guest") // 默认参数
lastname := c.Query("lastname")

c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
})
router.Run()
}

POST参数

func main(){
router := gin.Default()
router.POST("/form_post", func(c *gin.Context) {
message := c.PostForm("message")
nick := c.DefaultPostForm("nick", "anonymous")

c.JSON(http.StatusOK, gin.H{
"status": gin.H{
"status_code": http.StatusOK,
"status": "ok",
},
"message": message,
"nick": nick,
})
})
}