1、以[]byte方式返回
func main() {
r := gin.Default()
r.Handle("GET", "/hello", func(context *gin.Context) {
context.Writer.Write([]byte("hello,"))
})
r.Run()
}
2、以string方式返回结果
func main() {
r := gin.Default()
r.Handle("GET", "/hello", func(context *gin.Context) {
context.Writer.WriteString("hello,")
})
r.Run()
}
3、以JSON方式返回结果
r.POST("/hello", func(context *gin.Context) {
context.JSON(200, map[string]interface{}{
"code": 1,
"mess": "succ",
})
})
这里使用context.JSON方法进行调用就可以返回json格式,第一个参数是http请求的状态码,第二个参数是map[string]interface{}
也可以使用结构体来替换map类型
r.POST("/hellojson", func(context *gin.Context) {
res := Result{
Code: 1,
Msg: "ok",
}
context.JSON(200, &res)
})
type Result struct {
Code int
Msg string
}
2个的区别就是一个传递的是map,一个传递的是结构体。
4、以html方式返回结果
context.HTML(http.StatusOK,"./index.html",gin.H{
"name":"fq",
})
第一个参数还是http状态码,第二个参数是页面,第三个参数是后台传递给前端的参数。