?官网 https://gin-gonic.com/docs/
开源作者推荐:https://www.sohamkamani.com/
中文看云文档
获取传参
https://gin-gonic.com/zh-cn/docs/examples/querystring-param/
func GetChuanCan( c *gin.Context) {
var name = c.Query("name")
msg:="recive get args:"+name
c.String(200,msg)
}
json返回
?
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
var m1 = map[string]interface{}{
"name":"tom",
"city":"cs",
"sex":"男",
}
func main() {
r:=gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200,m1)
})
r.Run()
}
?
···
##### Struct 转 JSON
```go
?
package main
import "github.com/gin-gonic/gin"
type student struct {
Name string
Sex string
}
func main() {
r := gin.Default()
r.GET("/hello", func(c *gin.Context) {
c.JSON(200, student{Name: "tom",Sex: "man"})
})
r.Run(":8000")
}
?
自定义JSON字段名称
?
package main
import "github.com/gin-gonic/gin"
type student struct {
Name string `json:"name"`
Sex string `json:"sex"`
}
func main() {
r := gin.Default()
r.GET("/hello", func(c *gin.Context) {
c.JSON(200, student{Name: "tom",Sex: "man"})
})
r.Run(":8000")
}
?
返回json列表
?
package main
import "github.com/gin-gonic/gin"
type student struct {
Name string `json:"name"`
Sex string `json:"sex"`
}
func main() {
r := gin.Default()
all_student := []student{{Name: "tom",Sex: "man"},{Name: "nick",Sex: "woman"}}
r.GET("/hello", func(c *gin.Context) {
c.IndentedJSON(200, all_student)
})
r.Run(":8000")
}
?
?模块化
?
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func getUser(c *gin.Context) {
id := c.Param("id")
name := c.Param("name")
json := gin.H{
"data": id,
"name": name,
}
c.JSON(http.StatusOK, json)
}
func SayHello(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "hello,"+name)
}
func main() {
r := gin.Default()
r.GET("/sayHello/:name", SayHello)
r.GET("/test/:id/:name", getUser)
r.Run(":9090")
}
?
|