重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
Gin是用Go(Golang)编写的一个网页框架。它具有类似马提尼的API,具有更好的性能,由于httprouter,速度提高了40倍。 乌龟运维
创新互联-专业网站定制、快速模板网站建设、高性价比修文网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式修文网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖修文地区。费用合理售后完善,十年实体公司更值得信赖。
1 2 | #在example.go文件中假定以下代码 $catexample.go |
1 2 3 4 5 6 7 8 9 10 11 12 13 | packagemain
import"github.com/gin-gonic/gin"
funcmain(){ r:=gin.Default() r.GET("/ping",func(c *gin.Context){ c.JSON(200,gin.H{ "message":"pong", }) }) r.Run()// listen and serve on 0.0.0.0:8080 } |
1 2 | # run example.go and visit 0.0.0.0:8080/ping on browser $gorunexample.go |
Gin uses a custom version of HttpRouter
See all benchmarks
Benchmark name | (1) | (2) | (3) | (4) |
---|---|---|---|---|
BenchmarkGin_GithubAll | 30000 | 48375 | 0 | 0 |
BenchmarkAce_GithubAll | 10000 | 134059 | 13792 | 167 |
BenchmarkBear_GithubAll | 5000 | 534445 | 86448 | 943 |
BenchmarkBeego_GithubAll | 3000 | 592444 | 74705 | 812 |
BenchmarkBone_GithubAll | 200 | 6957308 | 698784 | 8453 |
BenchmarkDenco_GithubAll | 10000 | 158819 | 20224 | 167 |
BenchmarkEcho_GithubAll | 10000 | 154700 | 6496 | 203 |
BenchmarkGocraftWeb_GithubAll | 3000 | 570806 | 131656 | 1686 |
BenchmarkGoji_GithubAll | 2000 | 818034 | 56112 | 334 |
BenchmarkGojiv2_GithubAll | 2000 | 1213973 | 274768 | 3712 |
BenchmarkGoJsonRest_GithubAll | 2000 | 785796 | 134371 | 2737 |
BenchmarkGoRestful_GithubAll | 300 | 5238188 | 689672 | 4519 |
BenchmarkGorillaMux_GithubAll | 100 | 10257726 | 211840 | 2272 |
BenchmarkHttpRouter_GithubAll | 20000 | 105414 | 13792 | 167 |
BenchmarkHttpTreeMux_GithubAll | 10000 | 319934 | 65856 | 671 |
BenchmarkKocha_GithubAll | 10000 | 209442 | 23304 | 843 |
BenchmarkLARS_GithubAll | 20000 | 62565 | 0 | 0 |
BenchmarkMacaron_GithubAll | 2000 | 1161270 | 204194 | 2000 |
BenchmarkMartini_GithubAll | 200 | 9991713 | 226549 | 2325 |
BenchmarkPat_GithubAll | 200 | 5590793 | 1499568 | 27435 |
BenchmarkPossum_GithubAll | 10000 | 319768 | 84448 | 609 |
BenchmarkR2router_GithubAll | 10000 | 305134 | 77328 | 979 |
BenchmarkRivet_GithubAll | 10000 | 132134 | 16272 | 167 |
BenchmarkTango_GithubAll | 3000 | 552754 | 63826 | 1618 |
BenchmarkTigerTonic_GithubAll | 1000 | 1439483 | 239104 | 5374 |
BenchmarkTraffic_GithubAll | 100 | 11383067 | 2659329 | 21848 |
BenchmarkVulcan_GithubAll | 5000 | 394253 | 19894 | 609 |
(1):总重复次数达到的时间越长,意味着越有信心的结果
(2):单次重复持续时间(ns / op),越低越好
(3):堆内存(B / op),越低越好
(4):每个重复的平均分配(分配/操作),越低越好
零分配路由器。
仍然是最快的http路由器和框架。从路由到写作。
完整的单元测试套件
测试战斗
API冻结,新版本不会破坏你的代码。
下载并安装它
1 | gogetgithub.com/gin-gonic/gin |
在你的代码中导入它:
1 | import"github.com/gin-gonic/gin" |
(可选)导入net/http
。例如,如果使用常量如http.StatusOK
。
1 | import"net/http" |
go get
govendor
1 | $gogetgithub.com/kardianos/govendor |
创建你的项目文件夹cd
到里面
1 | $mkdir-p$GOPATH/src/github.com/myusername/project&&cd"$_" |
Vendor init your project and add gin
1 2 | $govendorinit $govendorfetchgithub.com/gin-gonic/gin@v1.2 |
在项目中复制起始模板
1 | $curlhttps://raw.githubusercontent.com/gin-gonic/gin/master/examples/basic/main.go > main.go |
Run your project
1 | $gorunmain.go |
Ginencoding/json
用作默认的json包,但你可以通过从其他标签建立更改为jsoniter。
1 | $gobuild-tags=jsoniter. |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | funcmain(){ // Disable Console Color // gin.DisableConsoleColor()
// Creates a gin router with default middleware: // logger and recovery (crash-free) middleware router:=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)
// By default it serves on :8080 unless a // PORT environment variable was defined. router.Run() // router.Run(":3000") for a hard coded port } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | funcmain(){ router:=gin.Default()
// This handler will match /user/john but will not match neither /user/ or /user router.GET("/user/:name",func(c *gin.Context){ name:=c.Param("name") c.String(http.StatusOK,"Hello %s",name) })
// However, this one will match /user/john/ and also /user/john/send // If no other routers match /user/john, it will redirect to /user/john/ router.GET("/user/:name/*action",func(c *gin.Context){ name:=c.Param("name") action:=c.Param("action") message:=name+" is "+action c.String(http.StatusOK,message) })
router.Run(":8080") } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | funcmain(){ router:=gin.Default()
// Query string parameters are parsed using the existing underlying request object. // The request responds to a url matching: /welcome?firstname=Jane&lastname=Doe router.GET("/welcome",func(c *gin.Context){ firstname:=c.DefaultQuery("firstname","Guest") lastname:=c.Query("lastname")// shortcut for c.Request.URL.Query().Get("lastname")
c.String(http.StatusOK,"Hello %s %s",firstname,lastname) }) router.Run(":8080") } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | funcmain(){ router:=gin.Default()
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") } |
1 2 3 4 | POST/post?id=1234&page=1HTTP/1.1 Content-Type:application/x-www-form-urlencoded
name=manu&message=this_is_great |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | funcmain(){ router:=gin.Default()
router.POST("/post",func(c *gin.Context){
id:=c.Query("id") page:=c.DefaultQuery("page","0") name:=c.PostForm("name") message:=c.PostForm("message")
fmt.Printf("id: %s; page: %s; name: %s; message: %s",id,page,name,message) }) router.Run(":8080") } |
1 | id:1234;page:1;name:manu;message:this_is_great |
引用问题#774和详细示例代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | funcmain(){ router:=gin.Default() // Set a lower memory limit for multipart forms (default is 32 MiB) // router.MaxMultipartMemory = 8 << 20 // 8 MiB router.POST("/upload",func(c *gin.Context){ // single file file,_:=c.FormFile("file") log.Println(file.Filename)
// Upload the file to specific dst. // c.SaveUploadedFile(file, dst)
c.String(http.StatusOK,fmt.Sprintf("'%s' uploaded!",file.Filename)) }) router.Run(":8080") } |
How to curl
:
1 2 3 | curl-XPOSThttp://localhost:8080/upload \ -F"file=@/Users/appleboy/test.zip"\ -H"Content-Type: multipart/form-data" |
查看详细的示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | funcmain(){ router:=gin.Default() // Set a lower memory limit for multipart forms (default is 32 MiB) // router.MaxMultipartMemory = 8 << 20 // 8 MiB router.POST("/upload",func(c *gin.Context){ // Multipart form form,_:=c.MultipartForm() files:=form.File["upload[]"]
for_,file:=rangefiles{ log.Println(file.Filename)
// Upload the file to specific dst. // c.SaveUploadedFile(file, dst) } c.String(http.StatusOK,fmt.Sprintf("%d files uploaded!",len(files))) }) router.Run(":8080") } |
How to curl
:
1 2 3 4 | curl-XPOSThttp://localhost:8080/upload \ -F"upload[]=@/Users/appleboy/test1.zip"\ -F"upload[]=@/Users/appleboy/test2.zip"\ -H"Content-Type: multipart/form-data" |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | funcmain(){ router:=gin.Default()
// Simple group: v1 v1:=router.Group("/v1") { v1.POST("/login",loginEndpoint) v1.POST("/submit",submitEndpoint) v1.POST("/read",readEndpoint) }
// Simple group: v2 v2:=router.Group("/v2") { v2.POST("/login",loginEndpoint) v2.POST("/submit",submitEndpoint) v2.POST("/read",readEndpoint) }
router.Run(":8080") } |
使用
1 | r:=gin.New() |
代替
1 2 | // Default With the Logger and Recovery middleware already attached r:=gin.Default() |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | funcmain(){ // Creates a router without any middleware by default r:=gin.New()
// Global middleware // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release. // By default gin.DefaultWriter = os.Stdout r.Use(gin.Logger())
// Recovery middleware recovers from any panics and writes a 500 if there was one. r.Use(gin.Recovery())
// Per route middleware, you can add as many as you desire. r.GET("/benchmark",MyBenchLogger(),benchEndpoint)
// Authorization group // authorized := r.Group("/", AuthRequired()) // exactly the same as: authorized:=r.Group("/") // per group middleware! in this case we use the custom created // AuthRequired() middleware just in the "authorized" group. authorized.Use(AuthRequired()) { authorized.POST("/login",loginEndpoint) 文章名称:GinWebFramework中文版 本文路径:http://cqcxhl.cn/article/phoceo.html 其他资讯 |