gin框架学习
安装
go get -u github.com/gin-gonic/gin
示例
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
// 创建一个默认的路由引擎
r := gin.Default()
// GET:请求方式;/hello:请求的路径
// 当客户端以GET方法请求/hello路径时,会执行后面的匿名函数
r.GET("/hello", func(c *gin.Context) {
// c.JSON:返回JSON格式的数据
c.JSON(200, gin.H{
"message": "Hello world!",
})
})
// 启动HTTP服务,默认在0.0.0.0:8080启动服务
r.Run()
}
gin.Default():func gin.Default() *gin.Engine
Default returns an Engine instance with the Logger and Recovery middleware already attached
r.GET():func (*gin.RouterGroup).GET(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes
GET is a shortcut for router.Handle("GET", path, handlers).
r.run():func (*gin.Engine).Run(addr ...string) (err error)
Run attaches the router to a http.Server and starts listening and serving HTTP requests. It is a shortcut for http.ListenAndServe(addr, router) Note: this method will block the calling goroutine indefinitely unless an error happens.
RESTful API
REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移”或“表现层状态转化”。
简单来说,REST的含义就是客户端与Web服务器之间进行交互的时候,使用HTTP协议中的4个请求方法代表不同的动作。
- GET用来获取资源
- POST用来新建资源
- PUT用来更新资源
- DELETE用来删除资源。
func main() {
r := gin.Default()
r.GET("/book", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "GET",
})
})
r.POST("/book", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "POST",
})
})
r.PUT("/book", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "PUT",
})
})
r.DELETE("/book", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "DELETE",
})
})
}
html响应
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default() // 默认路由
r.Static("css/", "./html/css") // 把路径中的"css/"替换成"./html/css"
r.Static("images/", "./html/images")
r.LoadHTMLGlob("tmpletes/*") // 加载html
r.GET("", func(ctx *gin.Context) {
ctx.HTML(200, "index.html", nil)
})
r.Run(":9090") // 运行端口
}
r.Static()函数用于将静态资源(例如样式表、脚本文件、图片等)与HTTP路由进行映射。这样可以让客户端通过相应的URL路径访问这些静态资源
r.LoadHTMLGlob()函数用于加载HTML模板文件,并告诉Gin框架在哪个目录下寻找模板文件。该函数会根据提供的模板路径,加载所有匹配该路径模式的HTML模板文件。
只要提前预处理好这两个文件,大部分的html都可以实现响应了
以下内容取自其他博客:
返回html
先要使用 LoadHTMLGlob()或者LoadHTMLFiles()方法来加载模板文件
//加载模板
router.LoadHTMLGlob("gin框架/templates/*")
//router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
//定义路由
router.GET("/tem", func(c *gin.Context) {
//根据完整文件名渲染模板,并传递参数
c.HTML(http.StatusOK, "index.html", gin.H{
"title": "Main website",
})
})
在模板中使用这个title,需要使用{{ .title }}
不同文件夹下模板名字可以相同,此时需要 LoadHTMLGlob() 加载两层模板路径。
router.LoadHTMLGlob("templates/**/*")
router.GET("/posts/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
"title": "Posts",
})
c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
"title": "Users",
})
})
文件响应:
// 在golang总,没有相对文件的路径,它只有相对项目的路径
// 网页请求这个静态目录的前缀, 第二个参数是一个目录,注意,前缀不要重复
router.StaticFS("/static", http.Dir("static/static"))
// 配置单个文件, 网页请求的路由,文件的路径
router.StaticFile("/titian.png", "static/titian.png")
重定向:
router.GET("/redirect", func(c *gin.Context) {
//支持内部和外部的重定向
c.Redirect(http.StatusMovedPermanently, "http://www.baidu.com/")
})
json 响应
router.GET("/json", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
})
// 结构体转json
router.GET("/moreJSON", func(c *gin.Context) {
// You also can use a struct
type Msg struct {
Name string `json:"user"`
Message string
Number int
}
msg := Msg{"fengfeng", "hey", 21}
// 注意 msg.Name 变成了 "user" 字段
// 以下方式都会输出 : {"user": "hanru", "Message": "hey", "Number": 123}
c.JSON(http.StatusOK, msg)
})
请求
获取querystring参数
func _query(c *gin.Context) {
fmt.Println(c.Query("user"))
fmt.Println(c.GetQuery("user"))
fmt.Println(c.QueryArray("user")) // 拿到多个相同的查询参数
fmt.Println(c.DefaultQuery("addr", "四川省"))
}
r.GET("/test", func(ctx *gin.Context) {
// 获取浏览器发送的请求
//两种获取请求的方式
a := ctx.DefaultQuery("name", "sb") // 取不到就用指定默认值
b := ctx.Query("age") // 获取含有age请求的参数
ctx.JSON(200, gin.H{
"name": a,
"age": b,
})
// 例如 /test?age=18&name=whopxx
})
引用: