从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 ...
随机推荐
- Redis快照持久化
Redis的持久化功能: redis为了内部数据的安全考虑,会把本身的数据以文件的形式保存到硬盘中一份,在服务器重启之后会自动把硬盘的数据恢复到内存(redis)里边. 数据保存到硬盘的过程就被称为” ...
- ANR机制
1.什么是ANR(Application Not Responding) 在Android中,应用程序的响应性是由ActivityManager和WindowManager系统服务监视的.当监测到以下 ...
- jstack 结果查看
首先可以用jstack -l pid >sample.dump把java进程的运行栈dump出来. 还可以用grep java.lang.Thread.State sample.dump | a ...
- nginx 配置 单页面应用的解决方案
server { listen 80; server_name example.com; root /var/www/example.com; gzip_static on; location / ...
- js的一些妙用
在一个数组上 直接附加上另一个数组: Array.prototype.push.apply(array1, array2); 将对象转换成一个数组: Array.prototype.slice.ca ...
- [转]Format a ui-grid grid column as currency
本文转自:https://stackoverflow.com/questions/27747184/format-a-ui-grid-grid-column-as-currency-rc-3-0 Yo ...
- Python——如何搭建Python的环境
最近在学Python,只知道python一般是用来写爬虫的,以前看过一个朋友用Python做的爬虫从妹子图网站上下载图片,觉得很有趣,自己也想学一学. 俗话说,万事开头难,首先第一步就是搭建Pytho ...
- lodop打印多页
定义全局变量 var loop = null; 加载时候打印 window.On_CLodop_Opened = function () { print(); //OpenPreview()是调用打印 ...
- 如何在没有https环境下使用webrtc
新版本的webrtc使用需要Https,但是在内网开发调试时,要配置Https环境比较麻烦,下面的方法是教你如何在http下使用webrtc 1,点桌面上的Chrome图票,右键->属性,把目票 ...
- [C语言] 数据结构-预备知识指针
所有的伟大源于一个勇敢的开始 数据结构预备知识 指针 1.指针:是C语言的灵魂,指针=地址 地址:内存单元的编号 指针变量:存放内存单元地址的变量 int *p;//p是指针变量,int *表示该p变 ...