从golang-gin-realworld-example-app项目学写httpapi (一)
https://wangzitian0.github.io/2013/06/29/zero-to-one-1/
https://github.com/gothinkster/golang-gin-realworld-example-app
目录结构
golang-gin-realworld-example-app/
├── articles
│ ├── doc.go
│ ├── models.go
│ ├── routers.go
│ ├── serializers.go
│ └── validators.go
├── common
│ ├── database.go
│ ├── unit_test.go
│ └── utils.go
├── doc.go
├── main.go
├── scripts
│ ├── coverage.sh
│ └── gofmt.sh
├── users
│ ├── doc.go
│ ├── middlewares.go
│ ├── models.go
│ ├── routers.go
│ ├── serializers.go
│ ├── unit_test.go
│ └── validators.go
└── vendor
└── vendor.json
https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/common/database.go
数据库
package common
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
// 定义结构体Database
type Database struct {
*gorm.DB
}
// 定义全局变量DB
var DB *gorm.DB
// 初始化数据库
func Init() *gorm.DB {
// 连接数据库
db, err := gorm.Open("sqlite3", "./../gorm.db")
//db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8mb4&parseTime=True&loc=Local")
if err != nil {
fmt.Println("db err: ", err)
}
// 设置闲置的连接数
db.DB().SetMaxIdleConns(10)
// 设置最大打开的连接数
db.DB().SetMaxOpenConns(100)
// 启用Logger,显示详细日志
db.LogMode(true)
DB = db
return DB
}
// 函数,获取数据库连接,建立连接池
func GetDB() *gorm.DB {
return DB
}
https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/common/utils.go
工具集
package common
import (
"fmt"
"math/rand"
"time"
"github.com/dgrijalva/jwt-go"
"gopkg.in/go-playground/validator.v8"
"github.com/gin-gonic/gin/binding"
"gopkg.in/gin-gonic/gin.v1"
)
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
// 函数 生成随机字符串
func RandString(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
// Keep this two config private, it should not expose to open source
const NBSecretPassword = "A String Very Very Very Strong!!@##$!@#$"
const NBRandomPassword = "A String Very Very Very Niubilty!!@##$!@#4"
// 函数 生成请求头使用的jwt_token
func GenToken(id uint) string {
jwt_token := jwt.New(jwt.GetSigningMethod("HS256"))
// Set some claims
jwt_token.Claims = jwt.MapClaims{
"id": id,
"exp": time.Now().Add(time.Hour * 24).Unix(),
}
// Sign and get the complete encoded token as a string
token, _ := jwt_token.SignedString([]byte(NBSecretPassword))
return token
}
// 自定义错误类型
// {"database": {"hello":"no such table", error: "not_exists"}}
type CommonError struct {
Errors map[string]interface{} `json:"errors"`
}
// 一般错误处理
func NewError(key string, err error) CommonError {
res := CommonError{}
res.Errors = make(map[string]interface{})
res.Errors[key] = err.Error()
return res
}
// gin的validator错误处理
// https://github.com/go-playground/validator/blob/v9/_examples/translations/main.go
func NewValidatorError(err error) CommonError {
res := CommonError{}
res.Errors = make(map[string]interface{})
errs := err.(validator.ValidationErrors)
for _, v := range errs {
// can translate each error one at a time.
//fmt.Println("gg",v.NameNamespace)
if v.Param != "" {
res.Errors[v.Field] = fmt.Sprintf("{%v: %v}", v.Tag, v.Param)
} else {
res.Errors[v.Field] = fmt.Sprintf("{key: %v}", v.Tag)
}
}
return res
}
// 变更gin-gonic的Bind函数,改变 c.MustBindWith() -> c.ShouldBindWith().
func Bind(c *gin.Context, obj interface{}) error {
b := binding.Default(c.Request.Method, c.ContentType())
//return c.MustBindWith(obj, b)
return c.ShouldBindWith(obj, b)
}
从golang-gin-realworld-example-app项目学写httpapi (一)的更多相关文章
- 从golang-gin-realworld-example-app项目学写httpapi (八)
https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/common/unit_test.go 单元测试 ...
- 从golang-gin-realworld-example-app项目学写httpapi (七)
https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/hello.go main调用 package ...
- 从golang-gin-realworld-example-app项目学写httpapi (六)
https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/validators.go 验证器 ...
- 从golang-gin-realworld-example-app项目学写httpapi (五)
https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/middlewares.go 中间件 ...
- 从golang-gin-realworld-example-app项目学写httpapi (四)
https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/routers.go 路由定义 pa ...
- 从golang-gin-realworld-example-app项目学写httpapi (三)
https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/serializers.go 序列化 ...
- 从golang-gin-realworld-example-app项目学写httpapi (二)
https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/models.go 模型定义 use ...
- Golang Gin 项目包依赖管理 godep 使用
Golang Gin 项目包依赖管理 godep 使用 标签(空格分隔): Go 在按照github.com/tools/godep文档go get完包以后,调整项目结构为$GOPATH/src/$P ...
- Golang Gin 项目使用 Swagger
Golang Gin 项目使用 Swagger 标签(空格分隔): Go 首先需要github.com/swaggo/gin-swagger和github.com/swaggo/gin-swagger ...
随机推荐
- R302指识别开发笔记
一.相关概念 1.存储容量:500枚指纹,地址范围0-499. 2.用户记事本:模块内部为用户开辟了512Bytes的FLASH空间用于存放用户数据该存储空间称为用户记事本,该记事本逻辑上被分成16个 ...
- WCF系列教程之WCF服务协定
本文参考自:http://www.cnblogs.com/wangweimutou/p/4422883.html,纯属读书笔记,加深记忆 一.服务协定简介: 1.WCF所有的服务协定层里面的服务接口, ...
- Zip文件格式
Overview This document describes the on-disk structure of a PKZip (Zip) file. The documentation curr ...
- package-info类解读
类不能带有public.private访问权限.package-info.java再怎么特殊,也是一个类文件,也会被编译成package-info.class,但是在package-info.java ...
- Chapter 6. Names
6.2. Names and Identifiers A name is used to refer to an entity declared in a program. There are two ...
- java.lang.IllegalArgumentException: Comparison method violates its general contract!
这个错误就是写比较器的时候少写了返回值的情况: 比如: Collections.sort(list, new Ordering<QtmSysUserListDto>() { @Overri ...
- android studio导入android studio工程
在导入其他android studio工程的时候因为gradle和sdk.tool等版本不一样,会导致android studio自动去后台下载,导致占用硬盘越来越大,最主要的时候会等待很久,不知道要 ...
- developer.android.google.cn
Android Studio官方 Android IDE https://developer.android.google.cn/studio/index.html 探索 Android Studio ...
- 完美世界-Java游戏开发-二面
时间:2017-03-30 时长:15分 类型:二面 面试官比较聊得来,人比较和善,游戏面试还是nice的,老铁 1. 自我介绍 2. 平时玩哪些游戏?端游.页游 3. Maven你是怎么使用的? 4 ...
- Axios的详细配置和相关使用
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中. Features 从浏览器中创建 XMLHttpRequests 从 node.js 创建 http ...