文档地址:https://github.com/skyhee/gin-doc-cn#basic-router
get 请求方式:
package main import "github.com/gin-gonic/gin" import "net/http" import "fmt" func main() { router := gin.Default() router.GET("/string/:name", func(c *gin.Context) { name := c.Param("name") fmt.Println("Hello %s", name) c.String(http.StatusOK, fmt.Sprintf("namne是: '%s'", name)) //c.JSON(http.StatusOK, msg) //c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) //c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) router.Run(":8080") }post 请求方式:
package main import "github.com/gin-gonic/gin" import "net/http" import "fmt" func main() { router:= gin.Default() //form router.POST("/form", func(c *gin.Context) { type0 := c.DefaultPostForm("type", "alert")//可设置默认值 msg := c.PostForm("msg") title := c.PostForm("title") fmt.Println("type is '%s', msg is '%s', title is '%s'", type0, msg, title) c.String(http.StatusOK, fmt.Sprintf("type is '%s', msg is '%s', title is '%s'", type0, msg, title)) }) router.Run(":8080") }数据自动解析绑定
package main import "github.com/gin-gonic/gin" import "net/http" //import "fmt" // Binding from JSON type Login struct { User string `form:"user" json:"user" binding:"required"` Password string `form:"password" json:"password" binding:"required"` } func main() { router:= gin.Default() // 绑定JSON的例子 ({"user": "manu", "password": "123"}) router.POST("/loginJSON", func(c *gin.Context) { var json Login if c.BindJSON(&json) == nil { if json.User == "manu" && json.Password == "123" { c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) } else { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) } } }) // 绑定普通表单的例子 (user=manu&password=123) router.POST("/loginForm", func(c *gin.Context) { var form Login // 根据请求头中 content-type 自动推断. if c.Bind(&form) == nil { if form.User == "manu" && form.Password == "123" { c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) } else { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) } } }) // 绑定多媒体表单的例子 (user=manu&password=123) /* router.POST("/login", func(c *gin.Context) { var form LoginForm // 你可以显式声明来绑定多媒体表单: // c.BindWith(&form, binding.Form) // 或者使用自动推断: if c.Bind(&form) == nil { if form.User == "user" && form.Password == "password" { c.JSON(200, gin.H{"status": "you are logged in"}) } else { c.JSON(401, gin.H{"status": "unauthorized"}) } } })*/ router.Run(":8080") }
