package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.String(200, "Hello, world")
})
// get 路径参数
r.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
// get query
r.GET("/users", func(c *gin.Context) {
name := c.Query("name")
role := c.DefaultQuery("role", "teacher")
c.String(http.StatusOK, "%s is %s", name, role)
})
// POST format 参数
r.POST("/form", func(c *gin.Context) {
username := c.PostForm("username")
password := c.DefaultPostForm("username", "123456") // 可设置默认值
c.JSON(http.StatusOK, gin.H{
"username": username,
"password": password,
})
})
// post 字典参数
r.POST("/post", func(c *gin.Context) {
var user User
c.BindJSON(&user)
fmt.Println("name", user.Name)
fmt.Println("age", user.Age)
c.JSON(http.StatusOK, gin.H{
"name": user.Name,
"age": user.Age,
})
})
r.Run()
}