gin实践

Posted chenguifeng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了gin实践相关的知识,希望对你有一定的参考价值。

煎鱼大佬的教程

技术图片

 

 

 技术图片

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_

blog.sql

/*
Navicat MySQL Data Transfer
Source Database       : blog
Target Server Type    : MYSQL
Target Server Version : 50639
File Encoding         : 65001
Date: 2020-01-26 20:30:26
*/

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for blog_article
-- ----------------------------
DROP TABLE IF EXISTS `blog_article`;    
CREATE TABLE `blog_article` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `tag_id` int(10) unsigned DEFAULT 0 COMMENT 标签ID,
    `title` varchar(100) DEFAULT ‘‘ COMMENT 文章标题,
    `desc` varchar(255) DEFAULT ‘‘ COMMENT 简述,
    `content` text COMMENT 内容,
    `cover_image_url` varchar(255) DEFAULT ‘‘ COMMENT 封面图片地址,
    `created_on` int(10) unsigned DEFAULT 0 COMMENT 新建时间,
    `created_by` varchar(100) DEFAULT ‘‘ COMMENT 创建人,
    `modified_on` int(10) unsigned DEFAULT 0 COMMENT 修改时间,
    `modified_by` varchar(255) DEFAULT ‘‘ COMMENT 修改人,
    `deleted_on` int(10) unsigned DEFAULT 0,
    `state` tinyint(3) unsigned DEFAULT 1 COMMET 删除时间,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=文章管理;

-- ----------------------------
-- Table structure for blog_auth
-- ----------------------------
DROP TABLE IF EXISTS `blog_auth`;
CREATE TABLE `blog_auth` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `username` varchar(50) DEFAULT ‘‘ COMMENT 账号,
    `password` varchar(50) DEFAULT ‘‘ COMMENT 密码,
    PRIMARY KEY(`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

INSERT INTO `blog_auth` (`id`, `username`, `password`) VALUE (1, test, test123);


-- ----------------------------
-- Table structure for blog_tag
-- ----------------------------
DROP TABLE IF EXISTS `blog_tag`;
CREATE TABLE `blog_tag` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `name` varchar(100) DEFAULT ‘‘ COMMENT 标签名称,
    `created_on` int(10) unsigned DEFAULT 0 COMMENT 创建时间,
    `created_by` varchar(100) DEFAULT ‘‘ COMMENT 创建人,
    `modified_on` int(10) unsigned DEFAULT 0 COMMENT 修改时间,
    `modified_by` varchar(100) DEFAULT ‘‘ COMMENT 修改人,
    `deleted_on` int(10) unsigned DEFAULT 0 COMMENT 删除时间,
    `state` tinyint(3) unsigned DEFAULT 1 COMMENT 状态 0为禁用, 1为启用,
    PRIMARY KEY(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=文章标签管理;

models.go

 1 package models
 2 
 3 import (
 4     "fmt"
 5     "log"
 6 
 7     "github.com/jinzhu/gorm"
 8 
 9     "go-gin-example/pkg/setting"
10 )
11 
12 var db *gorm.DB
13 
14 type Model struct {
15     ID         int `gorm:"primary_key" json:"id"`
16     CreatedOn  int `json:"created_on"`
17     ModifiedOn int `json:"modified_on"`
18 }
19 
20 func init() {
21     var (
22         err                                               error
23         dbType, dbName, user, password, host, tablePrefix string
24     )
25 
26     sec, err := setting.Cfg.GetSection("database")
27     if err != nil {
28         log.Fatal(2, "Fail to get section ‘database‘: %v", err)
29     }
30 
31     dbType = sec.Key("TYPE").String()
32     dbName = sec.Key("NAME").String()
33     user = sec.Key("USER").String()
34     password = sec.Key("PASSWORD").String()
35     host = sec.Key("HOST").String()
36     tablePrefix = sec.Key("TABLE_PREFIX").String()
37 
38     db, err = gorm.Open(dbType, fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
39         user,
40         password,
41         host,
42         dbName))
43 
44     if err != nil {
45         log.Println(err)
46     }
47 
48     gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
49         return tablePrefix + defaultTableName
50     }
51 
52     db.SingularTable(true)
53     db.LogMode(true)
54     db.DB().SetMaxIdleConns(10)
55     db.DB().SetMaxOpenConns(100)
56 }
57 
58 func CloseDB() {
59     defer db.Close()
60 }

code.go

 1 package e
 2 
 3 const (
 4     SUCCESS        = 200
 5     ERRPR          = 500
 6     INVALID_PARAMS = 400
 7 
 8     ERROR_EXIST_TAG         = 10001
 9     ERRPR_NOT_EXIST_TAG     = 10002
10     ERROR_NOT_EXIST_ARTICLE = 10003
11 
12     ERRPR_AUTH_CHECK_TOCKEN_FAIL    = 20001
13     ERROR_AUTH_CHECK_TOCKEN_TIMEOUT = 20002
14     ERROR_AUTH_TOKEN                = 20003
15     ERROR_AUTH                      = 20004
16 )

msg.go

 1 package e
 2 
 3 var MsgFlags = map[int]string{
 4     SUCCESS:                        "ok",
 5     ERROR:                          "fail",
 6     INVALID_PARAMS:                 "请求参数错误",
 7     ERROR_EXIST_TAG:                "已存在该标签名称",
 8     ERROR_NOT_EXIST_TAG:            "该标签不存在",
 9     ERROR_NOT_EXIST_ARTICLE:        "该文章不存在",
10     ERROR_AUTH_CHECK_TOKEN_FAIL:    "Token鉴权失败",
11     ERROR_AUTH_CHECK_TOKEN_TIMEOUT: "Token已超时",
12     ERROR_AUTH_TOKEN:               "Token生成失败",
13     ERROR_AUTH:                     "Token错误",
14 }
15 
16 func GetMsg(code int) string {
17     msg, ok := MsgFlags[code]
18     if ok {
19         return msg
20     }
21     return MsgFlags[ERROR]
22 }

setting.go

 1 package setting
 2 
 3 import (
 4     "log"
 5     "time"
 6 
 7     "github.com/go-ini/ini"
 8 )
 9 
10 var (
11     Cfg *ini.File
12 
13     RunMode string
14 
15     HTTPPort     int
16     ReadTimeout  time.Duration
17     WriteTimeout time.Duration
18 
19     PageSize  int
20     JwtSecret string
21 )
22 
23 func init() {
24     var err error
25     Cfg, err = ini.Load("conf/app.ini")
26     if err != nil {
27         log.Fatalf("Fail to parse ‘conf/app.ini‘: %v", err)
28     }
29 
30     LoadBase()
31     LoadServer()
32     LoadApp()
33 }
34 
35 func LoadBase() {
36     RunMode = Cfg.Section("").Key("RUN_MODE").MustString("debug")
37 }
38 
39 func LoadServer() {
40     sec, err := Cfg.GetSection("server")
41     if err != nil {
42         log.Fatalf("Fail to get section ‘server‘: %v", err)
43     }
44 
45     HTTPPort = sec.Key("HTTP_PORT").MustInt(8000)
46     ReadTimeout = time.Duration(sec.Key("READ_TIMEOUT").MustInt(60)) * time.Second
47     WriteTimeout = time.Duration(sec.Key("WRITE_TIMEOUT").MustInt(60)) * time.Second
48 }
49 
50 func LoadApp() {
51     sec, err := Cfg.GetSection("app")
52     if err != nil {
53         log.Fatalf("Fail to get section ‘app‘: %v", err)
54     }
55 
56     JwtSecret = sec.Key("JWT_SECRET").MustString("!@)*#)!@U#@*!@!)")
57     PageSize = sec.Key("PAGE_SIZE").MustInt(10)
58 }

pagination.go

 1 package util
 2 
 3 import (
 4     "github.com/gin-gonic/gin"
 5     "github.com/unknwon/com"
 6 
 7     "go-gin-example/pkg/setting"
 8 )
 9 
10 func GetPage(c *gin.Context) int {
11     result := 0
12     page, _ := com.StrTo(c.Query("page")).Int()
13     if page > 0 {
14         result = (page - 1) * setting.PageSize
15     }
16 
17     return result
18 }

main.go

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "net/http"
 6 
 7     "go-gin-example/pkg/setting"
 8     "github.com/gin-gonic/gin"
 9 )
10 
11 func main() {
12     router := gin.Default()
13     router.GET("/test", func(c *gin.Context) {
14         c.JSON(200, gin.H{
15             "message": "test",
16         })
17     })
18     s := &http.Server{
19         Addr:           fmt.Sprintf(":%d", setting.HTTPPort),
20         Handler:        router,
21         ReadTimeout:    setting.ReadTimeout,
22         WriteTimeout:   setting.WriteTimeout,
23         MaxHeaderBytes: 1 << 20,
24     }
25 
26     s.ListenAndServe()
27 }
28 // curl 127.0.0.1:8000/test

 

以上是关于gin实践的主要内容,如果未能解决你的问题,请参考以下文章

Golang Gin实践 番外 请入门 Makefile

Go Web 框架 Gin 实践8—为它加上Swagger,帅帅的文档

Golang实践录:使用gin框架实现文件上传转发功能

Golang实践录:使用gin框架实现转发功能:上传文件并转

Golang实践录:使用gin框架实现转发功能:上传文件并转

Golang实践录:使用gin实现http basic认证