postgres-驱动使用
简单结构:
项目名称:tttt
----service
----base.go
----models
----model.go
----main.go
驱动:github.com/go-pg/pg
model.go:
package models type User struct { Id uint `json:"id"` Username string `json:"username" sql:"type:varchar(255), notnull, unique" binding:"required"` Password string `json:"-" sql:"type:varchar(255), notnull" binding:"required"` FullName string `json:"full_name" sql:"type:varchar(255)"` Permissions []string `json:"permissions"` }
base.go:
package service import ( "github.com/go-pg/pg" "github.com/go-pg/pg/orm" "log" "tttt/models" ) var Service *serviceProxy type serviceProxy struct { postgres *pg.DB } func init() { Service = new(serviceProxy) opt, err := pg.ParseURL("postgres://testdb:testdb@localhost:5432/auth?sslmode=disable") if err != nil { panic(err) } Service.postgres = pg.Connect(opt) // 打印debug-sql调试 Service.postgres.OnQueryProcessed(func(event *pg.QueryProcessedEvent) { query, _ := event.FormattedQuery() log.Printf("[SQL]: %s", query) }) for _, model := range []interface{}{ &models.User{}, } { if err := Service.postgres.CreateTable(model, &orm.CreateTableOptions{ IfNotExists: true, FKConstraints: true, }); err != nil { panic(err) } } } func (s *serviceProxy) Close() { s.postgres.Close() }
main.go:
package main import ( "github.com/gin-gonic/gin" "tttt/service" ) func main() { defer func() { service.Service.Close() // 程序停止后,关闭连接 }() route := gin.Default() route.Run("0.0.0.0:5000") }
浙公网安备 33010602011771号