1. //返回json
r.GET("/getJson", controller.GetUserInfo)
- package main
-
- import (
- /*"net/http"*/
- "gin/src/main/controller"
- "github.com/gin-gonic/gin"
- )
-
-
- func main() {
- r := gin.Default()
-
- r.GET("/get", func(ctx *gin.Context) {
- ctx.String(200/*http.StatusOK*/, "hello word golang-web!")
- })
-
- r.POST("/user/post", func(ctx *gin.Context) {
- ctx.String(200, "这是一个post请求!")
- })
-
- r.PUT("/user/put", func(ctx *gin.Context) {
- ctx.String(200, "这是一个put请求!")
- })
-
- r.DELETE("/user/delete", func(ctx *gin.Context) {
- ctx.String(200, "这是一个delete请求!")
- })
-
-
- //返回json
- r.GET("/getJson", controller.GetUserInfo)
-
-
-
-
- r.Run(":9999")
- }
2.
- package controller
-
- import "github.com/gin-gonic/gin"
-
- func GetUserInfo(c *gin.Context) {
- ReturnSucess(c, 200, "sucess", "user info" , 1)
-
- }
3.
- package controller
-
-
- import "github.com/gin-gonic/gin"
-
-
- type JsonStruct struct {
- Code int //'json: "code"'
- Msg interface{} //'json: "msg"'
- Data interface{} //'json: "data"'
- Count int64 //'json: "count"'
- }
-
- func ReturnSucess(c *gin.Context, code int , msg interface{}, data interface{}, count int64) {
- json := &JsonStruct{Code: code, Msg: msg, Data: data, Count: count}
- c.JSON(200, json)
- }
-
- func ReturnError(c *gin.Context, code int , msg interface{}, data interface{}, count int64) {
- json := &JsonStruct{Code: code, Msg:msg, Data:data, Count:count}
- c.JSON(200, json)
- }
4.接口返回示例:
