从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 ...
随机推荐
- 14.Promise对象
1.Promise的含义 Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大.它由社区最早提出和实现,ES6将其写进了语言标准,统一了用法,原生提供了Pro ...
- 《LeetBook》leetcode题解(4): Median of Two Sorted Arrays[H]——两个有序数组中值问题
我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...
- Chapter 14. Blocks and Statements
14.5. Statements There are many kinds of statements in the Java programming language. Most correspon ...
- 用尾递归和普通递归实现n!算法,二者比较
尾递归 - Tail Recursion尾递归是针对传统的递归算法而言的, 传统的递归算法在很多时候被视为洪水猛兽. 它的名声狼籍, 好像永远和低效联系在一起.尾递归就是从最后开始计算, 每递归一次就 ...
- R语言paste函数
中许多字符串使用 paste() 函数来组合.它可以将任意数量的参数组合在一起. 语法 粘贴(paste)函数的基本语法是: paste(..., sep = " ", colla ...
- 在ViewDidLoad中往导航栈推ViewController报错
Unbalanced calls to begin/end appearance transitions for <YZPMainViewController: 0x7fa04b4970f0& ...
- Vue组件库
滴滴cube-ui https://didi.github.io/cube-ui/#/zh-CN/docs/quick-start 有赞开源Vant(适合做商城) https://tech.youza ...
- [转]使用ASP.NET Web API 2创建OData v4 终结点
本文转自:http://www.cnblogs.com/farb/p/ODataAspNetWebAPI.html 开放数据协议(Open Data Protocol[简称OData])是用于Web的 ...
- WCF-异步调用和两种客户端形式
当发布一个服务端之后,客户端可以通过服务端的元数据,用VS2010添加服务引用的方式生成对应的代码.并且可以选择生成相应的异步操作. WCF实现代码,Add操作延时5秒后再返回结果. [Service ...
- php中的namespace 命名空间
名字解释: namespace(命名空间),命名空间是从php5.3开始支持的功能.作用主要有两个:1.可以避免类名取得过长.2.当在多个框架配合使用时,同名的类之间不会冲突. 命名空间,看名字就知道 ...