代码
package main
import (
"github.com/gin-gonic/gin"
"net/http"
"strconv"
)
var id int = 0
// get处理函数
func t1_get(c *gin.Context) {
name := c.Query("name")
id += 1
c.JSON(http.StatusOK, gin.H{
"title": "get",
"msg": "hello " + name + " you are the " + strconv.Itoa(id) + "th guest !",
})
}
// 定义json序列化结构
type PostData struct {
Name string `json:"name"`
Tel string `json:"tel"`
Email string `json:"email"`
}
// post处理函数
func t1_post(c *gin.Context) {
var postData PostData
// 解析body部分
if err := c.ShouldBindBodyWithJSON(&postData); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
id += 1
// 设置返回值
c.JSON( http.StatusOK, gin.H{
"title": "post",
"content": postData,
"msg": strconv.Itoa(id) + "th guest !",
})
}
func main() {
// 创建服务
serv := gin.Default()
serv.UseH2C = true
// 创建路由
route := serv.Group("/test")
// 添加两个路由
route.GET("/t1", t1_get)
route.POST("/t1", t1_post)
// 启动
serv.Run(":3322")
}
创建 go.mod,内容 module gohttp
执行go mod tidy,自动查找并下载依赖。如果不能联网访问源的,注意设置GOPROXY代理。
运行

测试结果

发表回复