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 (一)的更多相关文章

  1. 从golang-gin-realworld-example-app项目学写httpapi (八)

    https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/common/unit_test.go 单元测试 ...

  2. 从golang-gin-realworld-example-app项目学写httpapi (七)

    https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/hello.go main调用 package ...

  3. 从golang-gin-realworld-example-app项目学写httpapi (六)

    https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/validators.go 验证器 ...

  4. 从golang-gin-realworld-example-app项目学写httpapi (五)

    https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/middlewares.go 中间件 ...

  5. 从golang-gin-realworld-example-app项目学写httpapi (四)

    https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/routers.go 路由定义 pa ...

  6. 从golang-gin-realworld-example-app项目学写httpapi (三)

    https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/serializers.go 序列化 ...

  7. 从golang-gin-realworld-example-app项目学写httpapi (二)

    https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/models.go 模型定义 use ...

  8. Golang Gin 项目包依赖管理 godep 使用

    Golang Gin 项目包依赖管理 godep 使用 标签(空格分隔): Go 在按照github.com/tools/godep文档go get完包以后,调整项目结构为$GOPATH/src/$P ...

  9. Golang Gin 项目使用 Swagger

    Golang Gin 项目使用 Swagger 标签(空格分隔): Go 首先需要github.com/swaggo/gin-swagger和github.com/swaggo/gin-swagger ...

随机推荐

  1. 2-6 js基础-ajax

    1.var oAjax=new XmlHttpRequest()//创建一个ajax对象,兼容非ie6 var oAjax=new ActiveXObject('Microsoft.XMLHTTP') ...

  2. MYSQL数据库的日志文件

    日志文件:用来记录MySQL实例对某种条件做出响应时写入的文件.如错误日志文件.二进制日志文件.慢查询日志文件.查询日志文件等. 错误日志 show variables like 'log_error ...

  3. 12 Callable & Future & FutureTask

    创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable接口. 这2种方式都有一个缺陷就是:在执行完任务之后无法获取执行结果. 如果需要获取执行结果,就必须通过共享变量或者使用 ...

  4. PTA (Advanced Level) 1016 Phone Bills

    Phone Bills A long-distance telephone company charges its customers by the following rules: Making a ...

  5. 使用jQuery实时监听input输入值的变化

    //jQuery实时监听input值变化 $("#email").on("input propertychange",function(){ var str = ...

  6. 多功能电子通讯录(涉及到了双向链表的使用,Linux文件编程等等)

    readme.txt //作为一个程序员,我们咋么能不写用户手册呢!MSP的我觉得用户体验是王道,苹果手机的用户体验的确不错!不过WP加油!我去,扯远了!赶紧看我的程序吧!  歡迎使用多功能電子通訊錄 ...

  7. javascript的ajax功能的概念和示例

    AJAX即“Asynchronous Javascript And XML”(异步JavaScript和XML). 个人理解:ajax就是无刷新提交,然后得到返回内容. 对应的不使用ajax时的传统网 ...

  8. Virtualbox/Vagrant安装

    它们分别是什么? VirtualBox: 号称是最强的免费虚拟机软件和VM类似. 不仅具有丰富的特色,而且性能也很优异. Vagrant: 是一个基于Ruby的工具,用于创建和部署虚拟化开发环境. 使 ...

  9. oracle数据库的安装与连接关键点

    一.window xp系统上安装Oracle Database 10G 解锁Scott.Hr账号并重置口令 远程连接数oracle数据库地址 二.在Mac系统上使用Navicat远程连接oracle数 ...

  10. 拆系数FFT(任意模数FFT)

    拆系数FFT 对于任意模数 \(mod\) 设\(m=\sqrt {mod}\) 把多项式\(A(x)\)和\(B(x)\)的系数都拆成\(a\times m+b\)的形式,时\(a, b\)都小于\ ...