使用go开发一个API
内容准备
-
go1.11
-
govendor
-
gin
-
jwt
-
xorm
-
supervisord
-
nginx
Govendor
项目使用 govendor
作为项目的包管理器,项目的代码结构如下:
- projectname
- controller
- model
- vendor
- vendor.json
- ...
- tests
- main.go
vendor 目录底下是当前项目说依赖的第三方包存放的地方。其中有一个 vendor.json
的文件是用来记录项目包的依赖情况。如果依赖包中的代码不想提交到 git
上,可以忽略掉,在.gitignore
文件内加上:
1
2
3vendor/*
!vendor/vendor.json
然后在服务器部署的时候只需要执行以下命令就可以拉取依赖代码:
1
govendor sync
需要注意的是,使用
govendor
所有的代码需要放在$GOPATH/src/
目录下。
gin+jwt+xorm 编写api
项目的api
部分使用gin
和jwt
以及xrom
编写。
部署
部署的阶段使用 nginx
+ supervisord
来完成。将编译完的程序使用 supervisord
管理起来,确保程序不会断线,然后使用 nginx
通过反向代理的方式开放接口,配置方式如下:
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
31server {
listen 80;
server_name xxxx;
return 301 https://$host$request_uri;
}
server{
listen 443;
server_name xxxx;
location / {
proxy_pass http://localhost:8080;
proxy_buffer_size 64k;
proxy_buffers 32 32k;
proxy_busy_buffers_size 128k;
}
\#ssl 配置
}
这样就完成了使用 gin
来完成最小的api
的发布。