将对Redis实例的引用传递给Gorilla / Mux Handler

时间:2017-04-29 12:39:58

标签: go redis gorilla

我在尝试使用Gorilla/MuxGo-Redis时试图弄脏手,但我在这里面临一点实施问题。

基本上我的项目结构如下:

enter image description here

redismanager.go 处理Redis客户端的初始化:

package redismanager

import (
    "fmt"
    "github.com/go-redis/redis"
)

func InitRedisClient() redis.Client {
    client := redis.NewClient(&redis.Options{
        Addr    : "localhost:6379",
        Password: "",
        DB      : 0, //default
    })

    pong, err := client.Ping().Result()
    if( err != nil ){
        fmt.Println("Cannot Initialize Redis Client ", err)
    }
    fmt.Println("Redis Client Successfully Initialized . . .", pong)

    return *client
}

main.go 调用redismanager.InitRedisClient并初始化mux.Handlers

package main

import (
    "github.com/gorilla/mux"
    "github.com/go-redis/redis"
    "net/http"
    "fmt"
    "log"
    "encoding/json"
    "io/ioutil"
    "../redismanager"
    "../api"
)

type RedisInstance struct {
     RInstance *redis.Client
}

func main() {

    //Initialize Redis Client
    client := redismanager.InitRedisClient()
    //Get current redis instance to get passed to different Gorilla-Mux Handlers
    redisHandler := &RedisInstance{RInstance:&client}

    //Initialize Router Handlers
    r := mux.NewRouter()
    r.HandleFunc("/todo", redisHandler.AddTodoHandler).
                                       Methods("POST")

    fmt.Println("Listening on port :8000 . . .")

    // Bind to a port and pass our router in
    log.Fatal(http.ListenAndServe(":8000", r))

}

现在,我可以在同一个文件中轻松定义并正常工作AddTodoHandler,如:

func (c *RedisInstance) AddTodoHandler(w http.ResponseWriter, r *http.Request) {
  . . . doSomething
}

但是,为了使事情更加模块化,我试图将所有这些RouteHandlers移到api包中的各自文件中。为了做到这一点,我需要传递对redisHandler的引用,但是当我尝试使用api包内的处理程序时,我遇到了一些困难。

例如,如果在主要内容中我添加:

r.HandleFunc("/todo/{id}", api.GetTodoHandler(&client)).
                                        Methods("GET") 

gettodo.go

package api

import (
    "net/http"
    "github.com/gorilla/mux"
    "fmt"
    "encoding/json"
    "github.com/go-redis/redis"
)

func GetTodoHandler(c *RedisInstance) func (w http.ResponseWriter, r *http.Request) {
    func (w http.ResponseWriter, r *http.Request) {
        . . . doSomething
    }
}

效果很好。

我仍然是Go的新手,即使经过多次研究和阅读,也没有找到任何更清洁的解决方案。

我的方法是正确的还是有更好的方法?

3 个答案:

答案 0 :(得分:1)

r.HandleFunc("/todo/{id}", redisHandler.api.GetTodoHandler).Methods("GET")

redisHandler中定义的main没有api字段,因此这自然无法编译。

如果您在RedisInstance包中重新定义了api类型,并且在特定于方法的文件中定义了该类型的处理程序方法,那么您可以初始化redisHandler使用api.RedisInstance类型,您可以删除main.RedisInstance类型定义:

package main

import (
    "github.com/gorilla/mux"
    "github.com/go-redis/redis"
    "net/http"
    "fmt"
    "log"
    "encoding/json"
    "io/ioutil"
    "../redismanager"
    "../api"
)

func main() {

    //Initialize Redis Client
    client := redismanager.InitRedisClient()
    //Get current redis instance to get passed to different Gorilla-Mux Handlers
    redisHandler := &api.RedisInstance{RInstance:&client}

    //Initialize Router Handlers
    r := mux.NewRouter()
    r.HandleFunc("/todo", redisHandler.AddTodoHandler).Methods("POST")
    r.HandleFunc("/todo/{id}", redisHandler.GetTodoHandler).Methods("GET")

    fmt.Println("Listening on port :8000 . . .")

    // Bind to a port and pass our router in
    log.Fatal(http.ListenAndServe(":8000", r))

}

答案 1 :(得分:1)

编写一个函数,将具有Redis实例参数的函数转换为HTTP处理程序:

func redisHandler(c *RedisInstance,
    f func(c *RedisInstance, w http.ResponseWriter, r *http.Request)) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { f(c, w, r) })
}

像这样编写API处理程序:

func AddTodoHandler(c *RedisInstance, w http.ResponseWriter, r *http.Request) {
    ...
}

像这样添加到多路复用:

r.Handler("/todo", redisHandler(client, api.AddTodoHandler)).Methods("POST")

其中client是Redis实例。

答案 2 :(得分:1)

我建议使用App结构来初始化数据库和路由。并且所有Redis方法都将在内部调用。 例如type App struct{Routes *mux.Router, DB *DB_TYPE}

并且将具有App.initializeRoutes方法。

type App struct {
    Router *mux.Router
    DB     *redis.NewClient
}

func (a *App) Run(addr string) {
    log.Fatal(http.ListenAndServe(":8000", a.Router))
}


func (a *App) Initialize(addr, password string, db int) error {
    // Connect postgres

    db, err := redis.NewClient(&redis.Options{
      Addr:     addr,
      Password: password,
      DB:       db,
    })
    if err != nil {
        return err
    }

    // Ping to connection
    err = db.Ping()
    if err != nil {
        return err
    }

    // Set db in Model
    a.DB = db
    a.Router = mux.NewRouter()
    a.initializeRoutes()
    return nil
}


func (a *App) initializeRoutes() {
    a.Router.HandleFunc("/todo", a.AddTodoHandler).Methods("POST")
    a.Router.HandleFunc("/todo/{id}", a.GetTodoHandler).Methods("GET")
}

// AddTodoHandler has access to DB, in your case Redis
// you can replace the steps for Redis.
func (a *App) AddTodoHandler() {
   //has access to DB
   a.DB
}

希望您能明白这一点,您甚至可以将模型工作提取到单独的Struct中,然后将其传递到 func