gin_day1路由创建以及多种响应方式
1.路由的创建
需要导入”github.com/gin-gonic/gin”
2.创建模板文件夹
r.LoadHTMLGlob("./templates/*")
|
3.创建首页get响应,返回string数据
r.GET("/",func(context *gin.Context)){ context.string(200,"值:%v","hello world") }
|

200 为状态码,中间是格式,后面是值
4.返回json数据
1.空接口类型json
r.GET("/json1",func(context *gin.Context)){ context.json(200,map[string]interface{}{ "success":200 "sb":你 }) }
|

2.返回结构体json
type Article struct{ Title string `json:"title"` Desc string `json:"desc"` Content string `json:"content"` }
|

后面是指以json数据时,返回title而不是Title
r.GET("/json2",func(context *gin.Context)){ a:=Article{ Title:"woshibiaoti", Desc:"woshidesc", Content:"woshineirong" } context.json(200,a) }
|
5.返回jsonp数据
r.GET("/jsonp",func(context *gin.Context)){ a:=Article{ Title:"woshibiaoti", Desc:"woshidesc", Content:"woshineirong" } context.jsonp(200,a) }
|

jsonp与json的区别在于jsonp可以加上回调函数 /josnp?callback==xxxx
6.返回xml数据
r.GET("/xml",func(context *gin.Context)){ context.XML(200,gin.H{ "successs":200 }) }
|

7.返回html页面
要返回html页面一定要设置模板文件夹
r.GET("/news",func(context *gin.Context)){ context.HTML(http.StatusOK,"news.html",gin.H{ "title":"woshibiaoti" }) }
|
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>{{.title}}</h1> </body> </html>
|
