gin的基本使用
  安装
go get -u github.com/gin-gonic/gin
 1
# 配置文件
安装
go get -u github.com/go-ini/ini
 1
编写配置文件app.ini
#debug or release
RUN_MODE = debug
[app]
PAGE_SIZE = 10
JWT_SECRET = 23347$040412
[server]
HTTP_PORT = 8000
READ_TIMEOUT = 60
WRITE_TIMEOUT = 60
[database]
TYPE = mysql
USER = 数据库账号
PASSWORD = 数据库密码
#127.0.0.1:3306
HOST = 数据库IP:数据库端口号
NAME = blog
TABLE_PREFIX = blog_
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
基本使用
package setting
import (
    "github.com/go-ini/ini"
)
var Cfg *ini.File
func init(){
    // 加载配置文件
    Cfg, err = ini.Load("conf/app.ini")
    if err != nil {
        log.Fatalf("Fail to parse 'conf/app.ini': %v", err)
    }
    var RunMode = Cfg.Section("").Key("RUN_MODE").MustString("debug")
    // 获取server段
    sec, err := Cfg.GetSection("server")
    if err != nil {
        log.Fatalf("Fail to get section 'server': %v", err)
    }
    HTTPPort := sec.Key("HTTP_PORT").MustInt(8000)
    ReadTimeout := time.Duration(sec.Key("READ_TIMEOUT").MustInt(60)) * time.Second
    WriteTimeout :=  time.Duration(sec.Key("WRITE_TIMEOUT").MustInt(60)) * time.Second
}
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 请求处理
c *gin.Context
// 获取json请求参数
type LoginForm struct {
    Username string `json:"username"`
    Password string `json:"password"`
}
var params LoginForm
if err := c.ShouldBindJSON(¶ms); err != nil {
    e.Error(c, err.Error())
    return
}
// params.Username
// 获取get参数, url?username=mrcdh
c.Query("username")
// 获取post参数, form-data
c.PostForm("username")
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 中间件
# 跨域处理
func Cors() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Header("Access-Control-Allow-Origin", "*") // 允许任何源进行访问,如果是特定源,请替换为实际域名
        c.Header("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,DELETE,OPTIONS")
        //c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With, X-Access-Token")
        c.Header("Access-Control-Allow-Headers", "*")
        c.Header("Access-Control-Allow-Credentials", "true") // 如果需要携带cookie则设置为true
        c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
        // 针对预检请求(OPTIONS方法),直接返回200 OK
        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(http.StatusNoContent)
        }
        c.Next()
    }
}
r.Use(Cors())
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 集成redis
上次更新: 2024/04/10, 16:21:11