当前位置: 首页 > 科技观察

GolangGinWebFramework-快速入门-参数分析

时间:2023-03-13 00:56:00 科技观察

Gin是由Golang编写的Web框架。其功能类似于另一个Go框架Martini(暂停维护https://github.com/go-martini/martini)。Gin内部使用了定制版的httprouter(一种轻量级高性能的HTTP请求Router,即多路复用器),速度比Martini快40倍,Gin性能强大,效率高,可扩展性强,赶快用起来吧!安装Go版本要求:Go1.12及以上1。执行以下命令安装最新版本的Gin$goget-ugithub.com/gin-gonic/gin2。在您的代码中导入导入“github.com/gin-gonic/gin”3。(可选)importnet/http包,如果要使用其中一个常量,比如http.StatusOK,需要importimport"net/http"快速开始编写main.go,编写如下代码,执行go运行main.go,访问http://localhost:8080/Ping,可以得到响应信息{"message":"pong"}packagemainimport"github.com/gin-gonic/gin"funcmain(){r:=gin.Default()//创建默认的Gin引擎Engine,内部默认启用日志和异常恢复中间件r.GET("/ping",func(c*gin.Context){c.JSON(200,gin.H{“消息”:“乒乓球”,})})r。Run()//Listenatlocalhost:8080default}Benchmark测试结果说明:Benchmark名称:Benchmark测试项Column(1):固定时间内完成的重复次数,值越大性能越好Column(2):执行单个重复任务消耗的纳秒数,单位ns/op,值越小越好Column(3):执行单个重复任务消耗的堆内存字节数,单位B/op,值越低越好Column(4):每个重复任务的平均内存分配数,单位allocs/op,值越低越好GinV1稳定版的特点是零内存分配router仍然是最快的htt完成路由器和框架的单元测试严格测试API版本冻结,新发布的版本兼容你的原始代码使用jsoniter编译jsoniter(https://github.com/json-iterator/go)是一个高性能的替代方案Golang标准库encoding/json和完全兼容的包Gin默认使用encoding/json包,但是可以使用下面的标签修改为jsoniter重新编译源码gobuild-tags=jsoniter。API示例可以访问源码查看更多接口示例代码:https://github.com/gin-gonic/examplesusingGET,POST,PUT,PATCH,DELETE,OPTIONSfuncmain(){//默认创建ginroutermiddleware://loggerandrecovery(crash-free)middlewarerouter:=gin.Default()router。GET("/someGet",getting)router.POST("/somePost",posting)router.PUT("/somePut",putting)router.DELETE("/someDelete",deleting)router.PATCH("/somePatch",patching)router.HEAD("/someHead",head)router.OPTIONS("/someOptions",options)//Bydefaultitserveson:8080unlessa//PORTenvironmentvariablewasdefined.router.Run()//router.Run(":3000")forahardcodedport指定端口}路径参数funcmain(){router:=gin.Default()//Thishandlerwillmatch/user/johnbutwillnotmatch/user/or/user//下面的路由只会匹配/user/username,不会匹配/user/或/userrouter.GET("/user/:name",func(c*gin.Context){name:=c.Param("name")//使用Param方法从路径获取参数c.String(http.StatusOK,"Hello%s",name)})//但是,thisonewillmatch/user/john/andalso/user/john/send//如果nootherrouters匹配/user/john,它会重定向到/user/john///带冒号的路由:和星号*可以匹配/user/username/或/user/username/action,如果/user/username不匹配其他路由,会自动跳转到/user/username/匹配router.GET("/user/:name/*action",func(c*gin.Context){name:=c.Param("name")action:=c.Param("action")message:=name+"is"+actionc.String(http.StatusOK,message)})//foreachmatchedrequestContextwillholdtherouteddefinition//请求上下文requestContext会保存所有匹配的路由定义到c.FullPath()方法router.POST("/user/:name/*action",func(c*gin.Context){c.FullPath()=="/user/:name/*action"//真})路线r.Run(":8080")}querystringparametersfuncmain(){router:=gin.Default()//Querystringparametersareparsedusingtheexistingunderlyingrequesttobject.//Therequestrespondstoaurlmatching:/welcome?firstname=Jane&lastname=Doe//发送测试请求:/welcome?firstname=Jane&lastname=Doerouter.GET("/welcome",func(c*gin.Context){firstname:=c.DefaultQuery("firstname","Guest")//如果没有获取到key值,则使用第二个参数作为默认值lastname:=c.Query("lastname")//上一行的完整写法:c.Request.URL.Query().Get("lastname")c.String(http.StatusOK,"Hello%s%s",firstname,lastname)})router.Run(":8080")}URL编码多个由两种数据类型组成的表单请求请求内容类型为:application/x-www-form-urlencodedContent-Type:application/x-www-form-urlencodedpackagemainimport"github.com/gin-gonic/gin"funcmain(){router:=gin.Default()//模拟表单提交:curl-XPOSThttp://localhost:8080/form_post-d"message=message&nick=nickname"router.POST("/form_post",func(c*gin.Context){message:=c.PostForm("message")nick:=c.DefaultPostForm("nick","anonymous")c.JSON(200,gin.H{"status":"posted","message":message,"nick":nick,})})router.Run(":8080")}//返回结果:{"message":"message","nick":"nickname","status":"posted"}查询和提交Post形式合并packagemainimport("fmt""github.com/gin-gonic/gin")funcmain(){router:=gin.Default()router.POST("/post",func(c*gin.Context){id:=c.Query("id")page:=c.DefaultQuery("page","0")name:=c.PostForm("name")消息:=c.PostForm("message")fmt.Printf("id:%s;page:%s;name:%s;message:%s\n",id,page,name,message)c.JSON(200,gin.H{"id":id,"page":page,"name":name,"message":message,})})router.Run(":8080")}模拟发送请求:curl-XPOSThttp://localhost:8080/post?id=1234&page=1-d"name=manu&message=this_is_great"返回结果:{"id":"1234","message":"this_is_great","name":"manu","page":"1"}withMapmappingasquerystringorPostformparameterfuncmain(){router:=gin.Default()router.POST("/post",func(c*gin.Context){ids:=c.QueryMap("ids")//获取查询参数中的Mapnames:=c.PostFormMap("names")//获取Mapfmt.Printf("ids:%v;names:%v\n",ids,names)})router.Run(":8080")}模拟请求:curl-XPOSThttp://localhost:8080/post?ids[a]=1234&ids[b]=hello-d"names[first]=thinkerou&names[second]=tianou"打印结果:ids:map[a:1234b:hello];names:map[first:thinkeroussecond:tianou]参考文档Gin官方仓库:https://github.com/gin-gonic/gin