What's Gin? | 青训营笔记

153 阅读3分钟

这是我参与「第三届青训营 -后端场」笔记创作活动的第 6 篇笔记

目录

  • Gin 是什么
  • Gin Benchmarks
  • Quick Start

Gin 是什么

Gin 是一个使用 Go 语言编写的 Web 框架,具有良好的性能和生产力

Gin Benchmarks

Benchmark name(1)(2)(3)(4)
BenchmarkGin_GithubAll4355027364 ns/op0 B/op0 allocs/op
BenchmarkAce_GithubAll4054329670 ns/op0 B/op0 allocs/op
BenchmarkAero_GithubAll5763220648 ns/op0 B/op0 allocs/op
BenchmarkBear_GithubAll9234216179 ns/op86448 B/op943 allocs/op
BenchmarkBeego_GithubAll7407243496 ns/op71456 B/op609 allocs/op
BenchmarkBone_GithubAll4202922835 ns/op720160 B/op8620 allocs/op
BenchmarkChi_GithubAll7620238331 ns/op87696 B/op609 allocs/op
BenchmarkDenco_GithubAll1835564494 ns/op20224 B/op167 allocs/op
BenchmarkEcho_GithubAll3125138479 ns/op0 B/op0 allocs/op
BenchmarkGocraftWeb_GithubAll4117300062 ns/op131656 B/op1686 allocs/op
BenchmarkGoji_GithubAll3274416158 ns/op56112 B/op334 allocs/op
BenchmarkGojiv2_GithubAll1402870518 ns/op352720 B/op4321 allocs/op
BenchmarkGoJsonRest_GithubAll2976401507 ns/op134371 B/op2737 allocs/op
BenchmarkGoRestful_GithubAll4102913158 ns/op910144 B/op2938 allocs/op
BenchmarkGorillaMux_GithubAll3463384987 ns/op251650 B/op1994 allocs/op
BenchmarkGowwwRouter_GithubAll10000143025 ns/op72144 B/op501 allocs/op
BenchmarkHttpRouter_GithubAll5593821360 ns/op0 B/op0 allocs/op
BenchmarkHttpTreeMux_GithubAll10000153944 ns/op65856 B/op671 allocs/op
BenchmarkKocha_GithubAll10000106315 ns/op23304 B/op843 allocs/op
BenchmarkLARS_GithubAll4777925084 ns/op0 B/op0 allocs/op
BenchmarkMacaron_GithubAll3266371907 ns/op149409 B/op1624 allocs/op
BenchmarkMartini_GithubAll3313444706 ns/op226551 B/op2325 allocs/op
BenchmarkPat_GithubAll2734381818 ns/op1483152 B/op26963 allocs/op
BenchmarkPossum_GithubAll10000164367 ns/op84448 B/op609 allocs/op
BenchmarkR2router_GithubAll10000160220 ns/op77328 B/op979 allocs/op
BenchmarkRivet_GithubAll1462582453 ns/op16272 B/op167 allocs/op
BenchmarkTango_GithubAll6255279611 ns/op63826 B/op1618 allocs/op
BenchmarkTigerTonic_GithubAll2008687874 ns/op193856 B/op4474 allocs/op
BenchmarkTraffic_GithubAll3553478508 ns/op820744 B/op14114 allocs/op
BenchmarkVulcan_GithubAll6885193333 ns/op19894 B/op609 allocs/op

Quick Start

使用 Gin 建立一个 Web 服务器是十分简单的,一个 Gin 的 Web 实例依赖一个 Engine,这个 Engine 包含了两个中间件 Logger 和 Recovery,后者用于恢复和处理程序在运行过程中的 panic,防止服务直接终止

package main

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

func main() {
	r := gin.Default() // 通过 Default 获取一个 Gin 的 Engine 实例,这个实例
                           // 包含了两个默认的中间件 Logger 和 Recovery
        
        // 通过 Engine 的 GET 方法来注册路由,第一个参数是路由地址,第二个参数
        // 是一个 gin.HandlerFunc 的可变参数,gin.HandlerFunc 是一个参数为 
        // *gin.Context 函数
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
        
        // 服务启动在本机的 80 端口
	r.Run("127.0.0.1:80")
}

现在可以打开浏览器或者使用接口测试工具访问 127.0.0.1/ping (注意:如果使用浏览器,使用的协议应该为 http,而不是 https)

图片.png