我刚刚开始尝试Go,并且希望重新实现用node编写的API服务器。
尝试使用依赖项注入来传递数据库上下文作为杜松子酒中间件时遇到了障碍。到目前为止,我已经将其设置为:
main.go:
package main
import (
"fmt"
"runtime"
"log"
"github.com/gin-gonic/gin"
"votesforschools.com/api/public"
"votesforschools.com/api/models"
)
type DB struct {
models.DataStore
}
func main() {
ConfigRuntime()
ConfigServer()
}
func Database(connectionString string) gin.HandlerFunc {
dbInstance, err := models.NewDB(connectionString)
if err != nil {
log.Panic(err)
}
db := &DB{dbInstance}
return func(c *gin.Context) {
c.Set("DB", db)
c.Next()
}
}
func ConfigRuntime() {
nuCPU := runtime.NumCPU()
runtime.GOMAXPROCS(nuCPU)
fmt.Printf("Running with %d CPUs\n", nuCPU)
}
func ConfigServer() {
gin.SetMode(gin.ReleaseMode)
router := gin.New()
router.Use(Database("<connectionstring>"))
router.GET("/public/current-vote-pack", public.GetCurrentVotePack)
router.Run(":1000")
}
型号/db.go
package models
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
type DataStore interface {
GetVotePack(id string) (*VotePack, error)
}
type DB struct {
*sql.DB
}
func NewDB(dataSource string) (*DB, error) {
db, err := sql.Open("mysql", dataSource)
if err != nil {
return nil, err
}
if err = db.Ping(); err != nil {
return nil, err
}
return &DB{db}, nil
}
型号/voicepack.go
package models
import (
"time"
"database/sql"
)
type VotePack struct {
id string
question string
description string
startDate time.Time
endDate time.Time
thankYou string
curriculum []string
}
func (db *DB) GetVotePack(id string) (*VotePack, error) {
var votePack *VotePack
err := db.QueryRow(
"SELECT id, question, description, start_date AS startDate, end_date AS endDate, thank_you AS thankYou, curriculum WHERE id = ?", id).Scan(
&votePack.id, &votePack.question, &votePack.description, &votePack.startDate, &votePack.endDate, &votePack.thankYou, &votePack.curriculum)
switch {
case err == sql.ErrNoRows:
return nil, err
case err != nil:
return nil, err
default:
return votePack, nil
}
}
因此,对于上述所有内容,我都希望将models.DataSource作为中间件传递,以便可以像这样进行访问:
public / public.go
package public
import (
"github.com/gin-gonic/gin"
)
func GetCurrentVotePack(context *gin.Context) {
db := context.Keys["DB"]
votePack, err := db.GetVotePack("c5039ecd-e774-4c19-a2b9-600c2134784d")
if err != nil{
context.String(404, "Votepack Not Found")
}
context.JSON(200, votePack)
}
但是我明白了 public\public.go:10: db.GetVotePack undefined (type interface {} is interface with no methods)
当我在调试器中检查(使用Webstorm和插件)时,db只是一个空对象。我正在努力做一个好人,避免使用全局变量
其中的值context.Keys
都是type interface{}
,因此在db
将*DB
其转换回该类型之前,将无法从type调用方法。
安全的方法:
db, ok := context.Keys["DB"].(*DB)
if !ok {
//Handle case of no *DB instance
}
// db is now a *DB value
不太安全的方法,如果context.Keys["DB"]
不是type的值,则会恐慌*DB
:
db := context.Keys["DB"].(*DB)
// db is now a *DB value
有效的Go对此进行了介绍。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句