我在玩一些Gorilla/Mux和Go-Redis时试图弄脏手,但我在这里面临一点实施问题。
基本上我有一个如下结构的项目:
其中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
包中的Handler进行编译时,我遇到了一些困难。
例如,如果在主要我添加:
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的新手,即使经过多次研究和阅读,也没有找到任何更清洁的解决方案。
我的方法是正确的还是有更好的方法?
编写一个函数,将带有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实例。
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))
}
我建议使用一个初始化DB和Routes的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
}
希望你明白这一点,你甚至可以将Model工作提取到一个单独的Struct中,然后在func中传递它