GinWebFramework中文版

Gin是用Go(Golang)編寫的一個網(wǎng)頁框架。它具有類似馬提尼的API,具有更好的性能,由于httprouter,速度提高了40倍。 烏龜運維

創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價比修文網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式修文網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋修文地區(qū)。費用合理售后完善,十年實體公司更值得信賴。

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):總重復(fù)次數(shù)達(dá)到的時間越長,意味著越有信心的結(jié)果

  • (2):單次重復(fù)持續(xù)時間(ns / op),越低越好

  • (3):堆內(nèi)存(B / op),越低越好

  • (4):每個重復(fù)的平均分配(分配/操作),越低越好

Gin v1. stable

  •  零分配路由器。

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

  •  完整的單元測試套件

  •  測試戰(zhàn)斗

  •  API凍結(jié),新版本不會破壞你的代碼。

開始使用它

  1. 下載并安裝它

1

gogetgithub.com/gin-gonic/gin

  1. 在你的代碼中導(dǎo)入它:

1

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

  1. (可選)導(dǎo)入net/http。例如,如果使用常量如http.StatusOK。

1

import"net/http"

使用像Govendor這樣的供應(yīng)商工具

  1. go get govendor

1

$gogetgithub.com/kardianos/govendor

  1. 創(chuàng)建你的項目文件夾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. 在項目中復(fù)制起始模板

1

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

  1. Run your project

1

$gorunmain.go

用jsoniter構(gòu)建

Ginencoding/json用作默認(rèn)的json包,但你可以通過從其他標(biāo)簽建立更改為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

}

路徑中的參數(shù)

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

}

查詢字符串參數(shù)

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和詳細(xì)示例代碼。

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

查看詳細(xì)的示例代碼

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

}

沒有中間件的默認(rèn)空白Gin

使用

1

r:=gin.New()

代替

1

2

// Default With the Logger and Recovery middleware already attached

r:=gin.Default()

使用中間件

<legend id="v9z5v"></legend>

<optgroup id="v9z5v"></optgroup>

    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)

    authorized.POST("/submit"

    本文名稱:GinWebFramework中文版
    標(biāo)題URL:http://muchs.cn/article40/phoceo.html

    成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供移動網(wǎng)站建設(shè)網(wǎng)站建設(shè)、虛擬主機、企業(yè)網(wǎng)站制作網(wǎng)頁設(shè)計公司、Google

    廣告

    聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)