GinWebFramework中文版

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

Benchmarks

Gin uses a custom version of HttpRouter

See all benchmarks

Benchmark name(1)(2)(3)(4)
BenchmarkGin_GithubAll300004837500
BenchmarkAce_GithubAll1000013405913792167
BenchmarkBear_GithubAll500053444586448943
BenchmarkBeego_GithubAll300059244474705812
BenchmarkBone_GithubAll20069573086987848453
BenchmarkDenco_GithubAll1000015881920224167
BenchmarkEcho_GithubAll100001547006496203
BenchmarkGocraftWeb_GithubAll30005708061316561686
BenchmarkGoji_GithubAll200081803456112334
BenchmarkGojiv2_GithubAll200012139732747683712
BenchmarkGoJsonRest_GithubAll20007857961343712737
BenchmarkGoRestful_GithubAll30052381886896724519
BenchmarkGorillaMux_GithubAll100102577262118402272
BenchmarkHttpRouter_GithubAll2000010541413792167
BenchmarkHttpTreeMux_GithubAll1000031993465856671
BenchmarkKocha_GithubAll1000020944223304843
BenchmarkLARS_GithubAll200006256500
BenchmarkMacaron_GithubAll200011612702041942000
BenchmarkMartini_GithubAll20099917132265492325
BenchmarkPat_GithubAll2005590793149956827435
BenchmarkPossum_GithubAll1000031976884448609
BenchmarkR2router_GithubAll1000030513477328979
BenchmarkRivet_GithubAll1000013213416272167
BenchmarkTango_GithubAll3000552754638261618
BenchmarkTigerTonic_GithubAll100014394832391045374
BenchmarkTraffic_GithubAll10011383067265932921848
BenchmarkVulcan_GithubAll500039425319894609
  • (1):总重复次数达到的时间越长,意味着越有信心的结果

  • (2):单次重复持续时间(ns / op),越低越好

  • (3):堆内存(B / op),越低越好

  • (4):每个重复的平均分配(分配/操作),越低越好

Gin v1. stable

  •  零分配路由器。

  • 仍然是最快的http路由器和框架。从路由到写作。

  •  完整的单元测试套件

  •  测试战斗

  •  API冻结,新版本不会破坏你的代码。

开始使用它

  1. 下载并安装它

1

gogetgithub.com/gin-gonic/gin

  1. 在你的代码中导入它:

1

import"github.com/gin-gonic/gin"

  1. (可选)导入net/http。例如,如果使用常量如http.StatusOK

1

import"net/http"

使用像Govendor这样的供应商工具

  1. go get govendor

1

$gogetgithub.com/kardianos/govendor

  1. 创建你的项目文件夹cd到里面

1

$mkdir-p$GOPATH/src/github.com/myusername/project&&cd"$_"

  1. Vendor init your project and add gin

1

2

$govendorinit

$govendorfetchgithub.com/gin-gonic/gin@v1.2

  1. 在项目中复制起始模板

1

$curlhttps://raw.githubusercontent.com/gin-gonic/gin/master/examples/basic/main.go > main.go

  1. Run your project

1

$gorunmain.go

用jsoniter构建

Ginencoding/json用作默认的json包,但你可以通过从其他标签建立更改为jsoniter。

1

$gobuild-tags=jsoniter.

API Examples

Using GET, POST, PUT, PATCH, DELETE and OPTIONS

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")

}

Multipart/Urlencoded Form

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")

}

Another example: query + post form

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

Upload files

单个文件

引用问题#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"

Multiple files

查看详细的示例代码

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"

Grouping routes

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")

}

没有中间件的默认空白Gin

使用

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中文版
URL标题:http://myzitong.com/article/phoceo.html