go web编程学习记录
阅读原文时间:2023年07月09日阅读:1

学习 https://segmentfault.com/a/1190000013297625的记录

简单demo

package main

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



gin-blog/
├── conf
├── middleware
├── models
├── pkg
├── routers
└── runtime
  • conf:用于存储配置文件
  • middleware:应用中间件
  • models:应用数据库模型
  • pkg:第三方包
  • routers 路由逻辑处理
  • runtime 应用运行时数据

创建数据库及表

API错误码包

pkg/e/code.go

package e

const (
SUCCESS = 200
ERROR = 500
INVALID_PARAMS = 400
<span class="hljs-attr">ERROR_EXIST_TAG = 10001
<span class="hljs-attr">ERROR_NOT_EXIST_TAG = 10002
<span class="hljs-attr">ERROR_NOT_EXIST_ARTICLE = 10003

<span class="hljs-attr">ERROR_AUTH_CHECK_TOKEN_FAIL = 20001
<span class="hljs-attr">ERROR_AUTH_CHECK_TOKEN_TIMEOUT = 20002
<span class="hljs-attr">ERROR_AUTH_TOKEN = 20003
<span class="hljs-attr">ERROR_AUTH = 20004

pkg/e/msg.go

package e

var MsgFlags = map[int]string {
SUCCESS : "ok",
ERROR : "fail",
INVALID_PARAMS : "请求参数错误",
ERROR_EXIST_TAG : "已存在该标签名称",
ERROR_NOT_EXIST_TAG : "该标签不存在",
ERROR_NOT_EXIST_ARTICLE : "该文章不存在",
ERROR_AUTH_CHECK_TOKEN_FAIL : "Token鉴权失败",
ERROR_AUTH_CHECK_TOKEN_TIMEOUT : "Token已超时",
ERROR_AUTH_TOKEN : "Token生成失败",
ERROR_AUTH : "Token错误",
}

func GetMsg(code int) string {
msg, ok := MsgFlags[code]
if ok {
return msg
}
<span class="hljs-keyword">return MsgFlags[ERROR]

model的处理

go&nbsp;get&nbsp;-u&nbsp;github.com/jinzhu/gorm

go&nbsp;get&nbsp;-u&nbsp;github.com/go-sql-driver/mysql

models/models.go

``package models

import (
"log"
"fmt"

"github.com/jinzhu/gorm"  
_ "github.com/jinzhu/gorm/dialects/mysql"

"gin-blog/pkg/setting"  

)

var db *gorm.DB

type Model struct {
ID int gorm:"primary_key" json:"id"
CreatedOn int json:"created_on"
ModifiedOn int json:"modified_on"
}

func init() {
var (
err error
dbType, dbName, user, password, host, tablePrefix string
)

sec, err := setting.Cfg.GetSection("database")  
if err != nil {  
    log.Fatal(2, "Fail to get section 'database': %v", err)  
}

dbType = sec.Key("TYPE").String()  
dbName = sec.Key("NAME").String()  
user = sec.Key("USER").String()  
password = sec.Key("PASSWORD").String()  
host = sec.Key("HOST").String()  
tablePrefix = sec.Key("TABLE_PREFIX").String()

db, err = gorm.Open(dbType, fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",  
    user,  
    password,  
    host,  
    dbName))

if err != nil {  
    log.Println(err)  
}

gorm.DefaultTableNameHandler = func (db *gorm.DB, defaultTableName string) string  {  
    return tablePrefix + defaultTableName;  
}

db.SingularTable(true)  
db.DB().SetMaxIdleConns(10)  
db.DB().SetMaxOpenConns(100)  

}

func CloseDB() {
defer db.Close()
}``