当前位置: 首页 > news >正文

gin框架

【狂神说】Gin框架一小时上手 | 快速转型GoWeb开发 | Go语言零基础教程_哔哩哔哩_bilibili

1.介绍

2.简单程序

1)gin.GET/POST/PUT/DELETE函数

Go Gin 简明教程 | 快速入门 | 极客兔兔 (geektutu.com)

我的理解是:这类函数就像是在监听接口一样,执行后一直在等待,没有捕捉到对应参数就没任何影响,捕捉到了就调用其对应的执行函数。

2)gin.Context

代表上下文信息,是一个结构体,一般用来处理Http请求和响应

Gin源码分析系列之Context篇 - 知乎 (zhihu.com)

20210814学习牛逼的gin.Context - 知乎 (zhihu.com)

3)context.JSON

给前端响应一个JSON信息

4)ginServer.Use(favicon.New("./day.ico")) 

给页面标签加一个ico

5)restful api

6)http状态码

const (StatusContinue           = 100 // RFC 9110, 15.2.1StatusSwitchingProtocols = 101 // RFC 9110, 15.2.2StatusProcessing         = 102 // RFC 2518, 10.1StatusEarlyHints         = 103 // RFC 8297StatusOK                   = 200 // RFC 9110, 15.3.1StatusCreated              = 201 // RFC 9110, 15.3.2StatusAccepted             = 202 // RFC 9110, 15.3.3StatusNonAuthoritativeInfo = 203 // RFC 9110, 15.3.4StatusNoContent            = 204 // RFC 9110, 15.3.5StatusResetContent         = 205 // RFC 9110, 15.3.6StatusPartialContent       = 206 // RFC 9110, 15.3.7StatusMultiStatus          = 207 // RFC 4918, 11.1StatusAlreadyReported      = 208 // RFC 5842, 7.1StatusIMUsed               = 226 // RFC 3229, 10.4.1StatusMultipleChoices   = 300 // RFC 9110, 15.4.1StatusMovedPermanently  = 301 // RFC 9110, 15.4.2StatusFound             = 302 // RFC 9110, 15.4.3StatusSeeOther          = 303 // RFC 9110, 15.4.4StatusNotModified       = 304 // RFC 9110, 15.4.5StatusUseProxy          = 305 // RFC 9110, 15.4.6_                       = 306 // RFC 9110, 15.4.7 (Unused)StatusTemporaryRedirect = 307 // RFC 9110, 15.4.8StatusPermanentRedirect = 308 // RFC 9110, 15.4.9StatusBadRequest                   = 400 // RFC 9110, 15.5.1StatusUnauthorized                 = 401 // RFC 9110, 15.5.2StatusPaymentRequired              = 402 // RFC 9110, 15.5.3StatusForbidden                    = 403 // RFC 9110, 15.5.4StatusNotFound                     = 404 // RFC 9110, 15.5.5StatusMethodNotAllowed             = 405 // RFC 9110, 15.5.6StatusNotAcceptable                = 406 // RFC 9110, 15.5.7StatusProxyAuthRequired            = 407 // RFC 9110, 15.5.8StatusRequestTimeout               = 408 // RFC 9110, 15.5.9StatusConflict                     = 409 // RFC 9110, 15.5.10StatusGone                         = 410 // RFC 9110, 15.5.11StatusLengthRequired               = 411 // RFC 9110, 15.5.12StatusPreconditionFailed           = 412 // RFC 9110, 15.5.13StatusRequestEntityTooLarge        = 413 // RFC 9110, 15.5.14StatusRequestURITooLong            = 414 // RFC 9110, 15.5.15StatusUnsupportedMediaType         = 415 // RFC 9110, 15.5.16StatusRequestedRangeNotSatisfiable = 416 // RFC 9110, 15.5.17StatusExpectationFailed            = 417 // RFC 9110, 15.5.18StatusTeapot                       = 418 // RFC 9110, 15.5.19 (Unused)StatusMisdirectedRequest           = 421 // RFC 9110, 15.5.20StatusUnprocessableEntity          = 422 // RFC 9110, 15.5.21StatusLocked                       = 423 // RFC 4918, 11.3StatusFailedDependency             = 424 // RFC 4918, 11.4StatusTooEarly                     = 425 // RFC 8470, 5.2.StatusUpgradeRequired              = 426 // RFC 9110, 15.5.22StatusPreconditionRequired         = 428 // RFC 6585, 3StatusTooManyRequests              = 429 // RFC 6585, 4StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3StatusInternalServerError           = 500 // RFC 9110, 15.6.1StatusNotImplemented                = 501 // RFC 9110, 15.6.2StatusBadGateway                    = 502 // RFC 9110, 15.6.3StatusServiceUnavailable            = 503 // RFC 9110, 15.6.4StatusGatewayTimeout                = 504 // RFC 9110, 15.6.5StatusHTTPVersionNotSupported       = 505 // RFC 9110, 15.6.6StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1StatusInsufficientStorage           = 507 // RFC 4918, 11.5StatusLoopDetected                  = 508 // RFC 5842, 7.2StatusNotExtended                   = 510 // RFC 2774, 7StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

3.给前端响应

发送请求和响应

给前端发送json和页面(静态资源)

package mainimport ("net/http""github.com/gin-gonic/gin""github.com/thinkerou/favicon"
)func main() {//·1.创建一个服务ginServer := gin.Default()ginServer.Use(favicon.New("./day.ico")) //加网站小icon//连接数据库之类,之后可以作为一个接口就可以给前端返回数据// //2.访问地址,处理我们的请求Request Response// //发送一个GET请求,如果url有hello,会执行后面的函数给前端返回信息// ginServer.GET("/hello", func(context *gin.Context) {// 	context.JSON(200, gin.H{"msg": "helloworld"})// })// ginServer.POST("/user", func(c *gin.Context) {// 	//返回json数据,状态码200就是http.StatusOK// 	c.JSON(200, gin.H{"msg": "post,user"})// })// ginServer.PUT("/user")// ginServer.DELETE("/user")//3.响应页面给前端//加载静态页面ginServer.LoadHTMLGlob("templates/*")//ginServer.LoadHTMLFiles("templates/index.html") //加载单个//4.加载资源文件(资源文件位置,根目录位置)ginServer.Static("/static", "./static")ginServer.GET("/index", func(c *gin.Context) {//返回页面c.HTML(http.StatusOK, "index.html", gin.H{"msg": "这是go后台传递来的数据...",})})//服务器端口,给一个服务端口,默认8080ginServer.Run(":8080") //一定有个冒号
}

4.获取请求中的参数

1)前端表单

package mainimport ("encoding/json""net/http""github.com/gin-gonic/gin""github.com/thinkerou/favicon"
)/*
固定格式:请求,处理请求函数
ginServer.POST("/user", func(c *gin.Context) {
})
*/
func main() {//·1.创建一个服务ginServer := gin.Default()ginServer.Use(favicon.New("./day.ico")) //加网站小icon//连接数据库之类,之后可以作为一个接口就可以给前端返回数据//3.响应页面给前端//加载静态页面ginServer.LoadHTMLGlob("templates/*")//ginServer.LoadHTMLFiles("templates/index.html") //加载单个//4.加载资源文件(资源文件位置,根目录位置)ginServer.Static("/static", "./static")ginServer.GET("/index", func(c *gin.Context) {//返回页面c.HTML(http.StatusOK, "index.html", gin.H{"msg": "这是go后台传递来的数据...",})})//7.获取前端表单数据ginServer.POST("/user/add", func(c *gin.Context) {//拿到数据username := c.PostForm("username")password := c.PostForm("password")//数据校验// if username == {// }//给前端返回数据c.JSON(http.StatusOK, gin.H{"msg":      "Ok","password": password,"username": username,})})//服务器端口,给一个服务端口,默认8080ginServer.Run(":8080") //一定有个冒号
}

 2)前端给后端传json

package mainimport ("encoding/json""net/http""github.com/gin-gonic/gin""github.com/thinkerou/favicon"
)/*
固定格式:请求,处理请求函数
ginServer.POST("/user", func(c *gin.Context) {
})
*/
func main() {//·1.创建一个服务ginServer := gin.Default()ginServer.Use(favicon.New("./day.ico")) //加网站小icon//前端给后端传jsonginServer.POST("/json", func(c *gin.Context) {//request.bodydata, _ := c.GetRawData()  //从请求体获取数据var m map[string]interface{}_ = json.Unmarshal(data, &m) //解析后端接收的json//给前端发送回去c.JSON(http.StatusOK,m)})//服务器端口,给一个服务端口,默认8080ginServer.Run(":8080") //一定有个冒号
}

3)?&传参

package mainimport ("net/http""github.com/gin-gonic/gin""github.com/thinkerou/favicon"
)/*
固定格式:请求,处理请求函数
ginServer.POST("/user", func(c *gin.Context) {
})
*/
func main() {//·1.创建一个服务ginServer := gin.Default()ginServer.Use(favicon.New("./day.ico")) //加网站小icon//?传参// url输入 /user/info?userid=xxx&username=kuangshenginServer.GET("/user/info", func(c *gin.Context) {userid := c.Query("userid") //接收前端问号传参的值username := c.Query("username")//返回json数据,状态码200就是http.StatusOKc.JSON(http.StatusOK, gin.H{"userid":   userid,"username": username,})})//服务器端口,给一个服务端口,默认8080ginServer.Run(":8080") //一定有个冒号
}

4)RESTful风格传参

package mainimport ("net/http""github.com/gin-gonic/gin""github.com/thinkerou/favicon"
)/*
固定格式:请求,处理请求函数
ginServer.POST("/user", func(c *gin.Context) {
})
*/
func main() {//·1.创建一个服务ginServer := gin.Default()ginServer.Use(favicon.New("./day.ico")) //加网站小icon//RESTful风格传参,冒号后自动接收参数//url输入 /user/info/1/ kuangshenginServer.GET("/user/info/:userid/:username", func(c *gin.Context) {userid := c.Param("userid")username := c.Param("username")//返回json数据,状态码200就是http.StatusOKc.JSON(http.StatusOK, gin.H{"userid":   userid,"username": username,})})//服务器端口,给一个服务端口,默认8080ginServer.Run(":8080") //一定有个冒号
}

5.路由,重定向

1)普通路由

该案例自动跳转必应

// 路由
func route(ginServer *gin.Engine) {ginServer.GET("test", func(context *gin.Context) {//重定向状态301context.Redirect(http.StatusMovedPermanently, "https://www.bing.com")})
}

2).404

只要输入的访问路径不被已知的请求处理,那么就是404状态,会被该请求捕获并跳转到404.

404页面需要提前加载一下静态资源

// 404页面
func noRoute(ginServer *gin.Engine) {ginServer.NoRoute(func(context *gin.Context) {context.HTML(http.StatusNotFound, "404.html", nil) //会从指定的静态资源路径下去找})

3)路由组

对一个路径下的不同分路径请求进行处理

// 路由组,相当于对一个路径下不同分路径一起做处理
func routeGroup(ginServer *gin.Engine) {userGroup := ginServer.Group("/user"){userGroup.GET("/add")userGroup.GET("/login")userGroup.GET("/logout")}orderGroup := ginServer.Group("/order"){orderGroup.GET("/add")orderGroup.GET("/delete")}}

6.拦截器

1)自定义中间件

流程:定义,注册,指定(可有可无)

注册中间件之后默认给所有请求使用,如果在某个请求里指定了,就只给这一个请求使用。

package mainimport ("encoding/json""log""net/http""github.com/gin-gonic/gin""github.com/thinkerou/favicon"
)// 自定义go中间件拦截器
func myHandler() gin.HandlerFunc {return func(context *gin.Context) {//自定义中间件设置的值,在后续处理只要调用了这个中间件的都可以拿到这里的参数context.Set("usersession", "userid-1")if true { //放行context.Next()} else { //阻止context.Abort()}}
}// 使用自定义中间件
func handler(ginServer *gin.Engine) {//这样请求被方法接收之前会先被中间件拦截处理,如果通过,才会被方法接收处理//?传参// url输入 /user/info2?userid=xxx&username=kuangshenginServer.GET("/user/info2",myHandler(), func(c *gin.Context) {//取出中间件的值usersession := c.MustGet("usersession").(string)log.Println(usersession)    //后台打印userid := c.Query("userid") //接收前端问号传参的值username := c.Query("username")c.JSON(http.StatusOK, gin.H{"userid":   userid,"username": username,})})
}func main() {//·1.创建一个服务ginServer := gin.Default()//注册中间件ginServer.Use(myHandler())ginServer.Use(favicon.New("./day.ico")) //加网站小icon//连接数据库之类,之后可以作为一个接口就可以给前端返回数据//使用自定义中间件handler(ginServer)//服务器端口,给一个服务端口,默认8080ginServer.Run(":8080") //一定有个冒号
}

http://www.lryc.cn/news/156642.html

相关文章:

  • Laravel 完整开源项目大全
  • Spring MVC @Controller和@RequestMapping注解
  • 软件架构之前后端分离架构服务器端高并发演进之路
  • 第4节-PhotoShop基础课程-Ps格式
  • C语言malloc函数学习
  • 从零开始学习deepsort目标追踪算法----原理和代码详解
  • 第三章 LInux多线程开发 3.1-3.5线程创建 终止 分离
  • 空间曲线的参数方程
  • 非华为机型如何体验HarmonyOS鸿蒙系统 刷写HarmonyOS鸿蒙GSI系统以及一些初步的bug修复
  • Flutter 生成小程序的混合 App 实践
  • 利用 Python-user-agents 解析 User_Agent
  • Java版企业电子招标采购系统源码Spring Cloud + Spring Boot +二次开发+ MybatisPlus + Redis
  • Mybatis如何给字段起别名?
  • php对接AWS S3云存储,上传S3及访问权限问题
  • java 实现单例模式
  • minio文件服务器开启https
  • 每日刷题(回溯法经典问题之子集)
  • PostgreSQL在进行除法时要注意
  • 开开心心带你学习MySQL数据库之第五篇
  • Geotools对geojson的解析
  • 【博客701】shell实现保留网络现场:ping失败时执行mtr
  • 放弃手写代码吧!用低代码你能生成各种源码
  • 什么程度才算精通 Linux?
  • jmeter中的__setProperty用法
  • vue基础知识六:v-show和v-if有什么区别?使用场景分别是什么?
  • SpringBoot几个常用的注解
  • 腾讯JAVA后端秋招面试总结
  • 随着iPhone 15降临,是时候扔掉所有的Lightning充电器了
  • huggingface 使用入门笔记
  • ASP.NET Core 中的 Razor Pages