我是golang的新手,我正在尝试用最好的方式来解决这个问题.
我有一系列我静态定义和传递的路由gorilla/mux
.我正在使用某些东西处理每个处理函数来处理请求和处理恐慌(主要是因为我可以理解包装是如何工作的).
我希望他们每个人都能够访问"上下文" - 一个每个http服务器一个结构,可能有数据库句柄,配置等等.我不想做的是使用静态全局变量.
我目前正在做的方式我可以给包装器访问上下文结构,但是我看不出如何将它放到实际的处理程序中,因为它希望它是一个http.HandlerFunc
.我认为我能做的就是转换http.HandlerFunc
成我自己的一种类型的接收器Context
(并且对包装器做同样的事情,但是(经过多次玩)我无法Handler()
接受这个.
我不禁想到我在这里遗漏了一些明显的东西.代码如下.
package main
import (
"fmt"
"github.com/gorilla/mux"
"html"
"log"
"net/http"
"time"
)
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Context struct {
route *Route
// imagine other stuff here, like database handles, config etc.
}
type Routes []Route
var routes = Routes{
Route{
"Index",
"GET",
"/",
index,
},
// imagine lots more routes here
}
func wrapLogger(inner http.Handler, context *Context) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner.ServeHTTP(w, r)
log.Printf(
"%s\t%s\t%s\t%s",
r.Method,
r.RequestURI,
context.route.Name,
time.Since(start),
)
})
}
func wrapPanic(inner http.Handler, context *Context) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Printf("panic caught: %+v", err)
http.Error(w, http.StatusText(500), 500)
}
}()
inner.ServeHTTP(w, r)
})
}
func newRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
// the context object is created here
context := Context {
&route,
// imagine more stuff here
}
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(wrapLogger(wrapPanic(route.HandlerFunc, &context), &context))
}
return router
}
func index(w http.ResponseWriter, r *http.Request) {
// I want this function to be able to have access to 'context'
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
}
func main() {
fmt.Print("Starting\n");
router := newRouter()
log.Fatal(http.ListenAndServe("127.0.0.1:8080", router))
}
Run Code Online (Sandbox Code Playgroud)
这是一种方法,但它似乎非常可怕.我不禁想到必须有一些更好的方法 - 也许是子类(?)http.Handler
.
package main
import (
"fmt"
"github.com/gorilla/mux"
"html"
"log"
"net/http"
"time"
)
type Route struct {
Name string
Method string
Pattern string
HandlerFunc ContextHandlerFunc
}
type Context struct {
route *Route
secret string
}
type ContextHandlerFunc func(c *Context, w http.ResponseWriter, r *http.Request)
type Routes []Route
var routes = Routes{
Route{
"Index",
"GET",
"/",
index,
},
}
func wrapLogger(inner ContextHandlerFunc) ContextHandlerFunc {
return func(c *Context, w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner(c, w, r)
log.Printf(
"%s\t%s\t%s\t%s",
r.Method,
r.RequestURI,
c.route.Name,
time.Since(start),
)
}
}
func wrapPanic(inner ContextHandlerFunc) ContextHandlerFunc {
return func(c *Context, w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Printf("panic caught: %+v", err)
http.Error(w, http.StatusText(500), 500)
}
}()
inner(c, w, r)
}
}
func newRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
context := Context{
&route,
"test",
}
router.Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
wrapLogger(wrapPanic(route.HandlerFunc))(&context, w, r)
})
}
return router
}
func index(c *Context, w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q secret is %s\n", html.EscapeString(r.URL.Path), c.secret)
}
func main() {
fmt.Print("Starting\n")
router := newRouter()
log.Fatal(http.ListenAndServe("127.0.0.1:8080", router))
}
Run Code Online (Sandbox Code Playgroud)
我正在学习Go,目前处于一个几乎完全相同的问题中,这就是我处理它的方式:
首先,我认为你错过了一个重要的细节:Go中没有全局变量.在你可以有一个变量最宽的范围是包范围.Go中唯一真正的全局变量是预先声明的标识符,例如true
和false
(并且您无法更改这些标识符或创建自己的标识符).
因此,将一个变量范围设置package main
为保存程序的上下文是完全正常的.来自C/C++背景,这花了我一点时间来习惯.由于变量是包范围的,因此它们不会遇到全局变量的问题.如果另一个包中的某些内容需要这样的变量,则必须明确地传递它.
在有意义的时候不要害怕使用包变量.这可以帮助您降低程序的复杂性,并且在很多情况下使您的自定义处理程序更加简单(调用http.HandlerFunc()
和传递闭包就足够了).
这样一个简单的处理程序可能如下所示:
func simpleHandler(c Context, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// FIXME Do something with our context
next.ServeHTTP(w, r)
})
}
Run Code Online (Sandbox Code Playgroud)
并被以下人士使用:
r = mux.NewRouter()
http.Handle("/", simpleHandler(c, r))
Run Code Online (Sandbox Code Playgroud)
如果您的需求更复杂,您可能需要实施自己的需求http.Handler
.请记住,a http.Handler
只是一个实现的接口ServeHTTP(w http.ResponseWriter, r *http.Request)
.
这是未经测试的,但应该让你大约95%的方式:
package main
import (
"net/http"
)
type complicatedHandler struct {
h http.Handler
opts ComplicatedOptions
}
type ComplicatedOptions struct {
// FIXME All of the variables you want to set for this handler
}
func (m complicatedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// FIXME Do stuff before serving page
// Call the next handler
m.h.ServeHTTP(w, r)
// FIXME Do stuff after serving page
}
func ComplicatedHandler(o ComplicatedOptions) func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return complicatedHandler{h, o}
}
}
Run Code Online (Sandbox Code Playgroud)
要使用它:
r := mux.NewRouter()
// FIXME: Add routes to the mux
opts := ComplicatedOptions{/* FIXME */}
myHandler := ComplicatedHandler(opts)
http.Handle("/", myHandler(r))
Run Code Online (Sandbox Code Playgroud)
对于更开发的处理程序示例,请参阅goji/httpauth中的basicAuth,此示例无耻地被删除.
进一步阅读: