Golang 的 Gorm Middleware

将 Gorm 注入到 Request 的 Context 中:

package middleware

import (
    "context"
    "github.com/jinzhu/gorm"
    "net/http"
)

func SetGormContext(ctx context.Context, orm *gorm.DB) context.Context {
    return context.WithValue(ctx, "db", orm)
}

func GetGormFromRequest(r *http.Request) *gorm.DB {

    return r.Context().Value("db").(*gorm.DB)
}

func GormMiddleWare(orm *gorm.DB) func (http.Handler) http.Handler {

    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

            ctx := SetGormContext(r.Context(), orm)
            next.ServeHTTP(w, r.WithContext(ctx))
        })
    }
}

使用:

package main

import (
    "./middleware"
    "github.com/gorilla/mux"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
    "log"
    "net/http"
    "time"
)

type Oauth struct {
    ID        uint `gorm:"primary_key"`
    Type int
    UserId int `gorm:"column:user_id"`
    Username string
    Email string
    CreatedAt time.Time
    UpdatedAt time.Time
}

func (Oauth) TableName() string {
    return "oauth"
}

func HomeHandler(w http.ResponseWriter, r *http.Request) {
    db := middleware.GetGormFromRequest(r)
    oauth := new(Oauth)
    db.First(oauth)
    w.Write([]byte(oauth.Username))
}

func main() {

    db, err := gorm.Open("mysql", "root:password@/dbname?charset=utf8mb4&parseTime=True&loc=Local")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    db.DB().SetMaxIdleConns(10)
    db.DB().SetMaxOpenConns(20)
    db.DB().SetConnMaxLifetime(time.Hour)

    route := mux.NewRouter()
    route.HandleFunc("/", HomeHandler)
    route.Use(middleware.GormMiddleWare(db))

    log.Fatal(http.ListenAndServe(":8080", route))
}