Golang uses the return result of the GIN framework

The command is returned in the format of []byte

func main() {
  r := gin.Default()
  r.Handle("GET", "/hello", func(context *gin.Context) {  
  context.Writer.Write([]byte("hello,"))
  })
  r.Run()
}

Returns the result as a string

func main() {
  r := gin.Default()
  r.Handle("GET", "/hello", func(context *gin.Context) {  
  context.Writer.WriteString("hello,")
  })
  r.Run()
}

The result is returned in JSON format

r.POST("/hello", func(context *gin.Context) {
  context.JSON(200, map[string]interface{}{
    "code": 1,
    "mess": "succ",
  })
  })

JSON method is used to return JSON format. The first parameter is the HTTP request status code, and the second parameter is map[string]interface{}.

You can also replace the map type with a construct

r.POST("/hellojson", func(context *gin.Context) {
  res := Result{
    Code: 1,
    Msg:  "ok",
  }
  context.JSON(200, &res)
})
type Result struct {
  Code int
  Msg  string
}

The difference between the two is that one passes a map and the other passes a structure.

Return the result as HTML

context.HTML(http.StatusOK,"./index.html",gin.H{
    "name":"fq",
})

The first parameter is again the HTTP status code, the second parameter is the page, and the third parameter is the parameter passed from the background to the front end.

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish