Gorm mux middleware

package middlewares

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

func GetDB(ctx context.Context) *gorm.DB {
    return ctx.Value("DB").(*gorm.DB)
}

func InjectDB(db *gorm.DB) func(next http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
            ctx := context.WithValue(r.Context(), "DB", db)
            next.ServeHTTP(w, r.WithContext(ctx))
        })
    }
}

注入 Context:

func main() {
    router := NewRouter()

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

    router.Use(middlewares.InjectDB(db))
    // Bind to a port and pass our router in
    log.Fatal(http.ListenAndServe(":8000", router))
}

使用:

type User struct {
    gorm.Model
    Name string
    Age int
}

type ResData struct {
    Code int `json:"code"`
    Msg string `json:"msg"`
    Data struct{
        Name string `json:"name"`
        Age int `json:"age"`
    } `json:"data"`
}

func IndexHandler(w http.ResponseWriter, r *http.Request) {
    db := middlewares.GetDB(r.Context())
    var user User
    db.First(&user)

    var result = new(ResData)
    result.Code = 0
    result.Msg = "ok"
    result.Data.Name = user.Name
    result.Data.Age = user.Age
    str, _ := json.Marshal(result)

    w.Header().Set("Content-Type", "Application/json;Charset=UTF-8")
    w.Write(str)
}