Gin 的介绍
Gin 是用 Go 编写的一个 Web 应用框架,对比其它主流的同类框架,他有更好的性能和更快的路由。由于其本身只是在官方 net/http 包的基础上做的完善,所以理解和上手很平滑。如果你现在开始做一套新的Api,我十分推荐你使用它。
Gin 的性能怎么样,需要数据说话,我们来看官方给出的表格:
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): Total Repetitions achieved in constant time, higher means more confident result
- (2): Single Repetition Duration (ns/op), lower is better
- (3): Heap Memory (B/op), lower is better
- (4): Average Allocations per Repetition (allocs/op), lower is better
查看更多的数据,可以查看 Benchmarks .
数据很亮眼,在编程体验上 Gin 也是毫不逊色。你仅仅只需要引入包、定义路由、编写 Handler ,你的应用就搭建完成了。实际上你只需要对 gin.Context 这个结构有深刻认识,就可以使用 Gin 流畅的编写代码了。
Gin 的使用
安装和更新
首次安装,使用 go get
命令获取即可。
//获取包:
vagrant@vagrant:/htdocs/go/src$ go get github.com/gin-gonic/gin
package golang.org/x/sys/unix: unrecognized import path "golang.org/x/sys/unix" (https fetch: Get https://golang.org/x/sys/unix?go-get=1: dial tcp 216.239.37.1:443: i/o timeout)
//查看go环境目录:
vagrant@vagrant:/etc/nginx/sites-available$ go env
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/vagrant/.cache/go-build"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/htdocs/go"
GOPROXY=""
GORACE=""
GOROOT="/usr/local/go"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build215351343=/tmp/go-build -gno-record-gcc-switches"
//创建golang.org/x目录:
vagrant@vagrant:/htdocs/go/src$ mkdir -p golang.org/x
vagrant@vagrant:/htdocs/go/src$ ll
total 4383
//重新拉取包:
vagrant@vagrant:/htdocs/go/src/golang.org/x$ git clone https://github.com/golang/sys.git
Cloning into 'sys'...
remote: Enumerating objects: 28, done.
remote: Counting objects: 100% (28/28), done.
remote: Compressing objects: 100% (23/23), done.
remote: Total 8031 (delta 7), reused 14 (delta 5), pack-reused 8003
Receiving objects: 100% (8031/8031), 6.32 MiB | 122.00 KiB/s, done.
Resolving deltas: 100% (6891/6891), done.
Checking connectivity... done.
Checking out files: 100% (426/426), done.
以上gin就安装好了,现在我们写个页面:api.go,内容如下:
package main import ( "github.com/gin-gonic/gin" "net/http" "fmt" ) type User struct { Username string `json: username` Password string `json: password` } var router *gin.Engine func main() { router = gin.Default() initializeRoutes() router.Run() } func initializeRoutes() { router.POST("/api", handleVerification) router.OPTIONS("/api", handleVerification) router.GET("/api", handleGet) } func handleGet(c *gin.Context) { message, _ := c.GetQuery("m") c.String(http.StatusOK, "Get works! you sent: "+message) } func handleVerification(c *gin.Context) { if c.Request.Method == "OPTIONS" { // setup headers c.Header("Allow", "POST, GET, OPTIONS") c.Header("Access-Control-Allow-Origin", "*") c.Header("Access-Control-Allow-Headers", "origin, content-type, accept") c.Header("Content-Type", "application/json") c.Status(http.StatusOK) } else if c.Request.Method == "POST" { var u User c.BindJSON(&u) c.JSON(http.StatusOK, gin.H{ "user": u.Username, "pass": u.Password, }) fmt.Printf("%+v\n", u.Username) fmt.Printf("%+v\n", u.Password) } }
编写api.html文件,内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
function init() {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://lch.go.com/api');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText))
}
};
xhr.send(JSON.stringify({
username: 'yoshie',
password: "456"
}));
}
</script>
</head>
<body onload="init()">
</body>
</html>
现在配置nginx,内容如下:
server {
listen 80;
server_name lch.go.com;
#root "/htdocs/go/src/";
charset utf-8;
access_log /var/log/nginx/lch.go.com-access.log;
location ~ \.(css|js|fonts|png|svg|html|txt)$ {
access_log on;
expires 1d;
root "/htdocs/go/src/";
try_files $uri @backend;
}
#try_files $uri/index.html $uri.html $uri @backend;
location / {
try_files /_not_exists_ @backend;
}
location @backend {
proxy_connect_timeout 60s;
proxy_read_timeout 60s;
client_max_body_size 2000m;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://127.0.0.1:8080;
}
}
重启nginx,并运行api.go文件,通过浏览器访问:
以上就是搭建了golang nginx 代理服务器来访问接口