go gin 响应数据
package mainimport ("fmt""github.com/gin-gonic/gin"
)type UserInfo struct {UserName string `json:"user_name"`Age int `json:"age"`Password string `json:"-"`
}func JsonTest(ctx *gin.Context) {a := UserInfo{"张三", 20, "123"}ctx.JSON(200, a)
}func Query1(c *gin.Context) {id := c.Query("id")c.String(200, id+"ces")
}func main() {fmt.Println("测试")router := gin.Default()router.GET("/index", func(ctx *gin.Context) {ctx.String(200, "Hello World~!")})router.GET("/json", JsonTest)router.GET("/query", Query1)router.Run(":8080")
}
package mainimport ("encoding/json""fmt""github.com/gin-gonic/gin"
)type ArticleModel struct {Title string `json:"title"`Content string `json:"content"`
}type Response struct {Code int `json:"code"`Data any `json:"data"`Msg string `json:"msg"`
}func _getList(c *gin.Context) {articleList := []ArticleModel{{"go语言入门", "这篇文章是讲解go的"},{"python语言入门", "这篇文章是讲解python的"},{"JavaScript语言入门", "这篇文章是讲解JavaScript的"},}// c.JSON(200, articleList)c.JSON(200, Response{0, articleList, "成功"})
}func _getDetail(c *gin.Context) {a := c.Param("id")fmt.Println(c.Param("id"))article := ArticleModel{"go语言入门", "这篇文章是讲解go的" + a,}c.JSON(200, Response{0, article, "成功"})
}/*
GET /articles 文章列表
GET /articles/:id 文章详情
POST /articles 添加文章
PUT /articles/:id 修改某一篇文章
DELETE /articles/:id 删除某一篇文章
*/func main() {fmt.Println("测试")router := gin.Default()router.GET("/articles", _getList)router.GET("/articles/:id", _getDetail)router.POST("/articles", _create)router.Run(":8080")
}func _bindJson(c *gin.Context, obj any) (err error) {body, _ := c.GetRawData()contentType := c.GetHeader("Content-Type")switch contentType {case "application/json":err = json.Unmarshal(body, &obj)if err != nil {fmt.Println(err.Error())return err}}return nil
}func _create(c *gin.Context) {var article ArticleModelerr := _bindJson(c, &article)if err != nil{fmt.Println(err)return}fmt.Println(article)c.JSON(200, Response{0, article, "添加成功"})
}