上周有点受到this article的启发,我正在重构一个应用程序,我必须更明确地将上下文(数据库池,会话存储等)传递给我的处理程序。
但是,我遇到的一个问题是没有全局模板映射,我的自定义处理程序类型上的ServeHTTP
方法(为了满足http.Handler
)无法再访问地图以呈现模板。
我需要保留全局templates
变量,或者将我的自定义处理程序类型重新定义为结构。
有没有更好的方法来实现这一目标?
func.go
package main
import (
"fmt"
"log"
"net/http"
"html/template"
"github.com/gorilla/sessions"
"github.com/jmoiron/sqlx"
"github.com/zenazn/goji/graceful"
"github.com/zenazn/goji/web"
)
var templates map[string]*template.Template
type appContext struct {
db *sqlx.DB
store *sessions.CookieStore
}
type appHandler func(w http.ResponseWriter, r *http.Request) (int, error)
func (ah appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// templates must be global for us to use it here
status, err := ah(w, r)
if err != nil {
log.Printf("HTTP %d: %q", status, err)
switch status {
case http.StatusNotFound:
// Would actually render a "http_404.tmpl" here...
http.NotFound(w, r)
case http.StatusInternalServerError:
// Would actually render a "http_500.tmpl" here
// (as above)
http.Error(w, http.StatusText(status), status)
default:
// Would actually render a "http_error.tmpl" here
// (as above)
http.Error(w, http.StatusText(status), status)
}
}
}
func main() {
// Both are 'nil' just for this example
context := &appContext{db: nil, store: nil}
r := web.New()
r.Get("/", appHandler(context.IndexHandler))
graceful.ListenAndServe(":8000", r)
}
func (app *appContext) IndexHandler(w http.ResponseWriter, r *http.Request) (int, error) {
fmt.Fprintf(w, "db is %q and store is %q", app.db, app.store)
return 200, nil
}
struct.go
package main
import (
"fmt"
"log"
"net/http"
"html/template"
"github.com/gorilla/sessions"
"github.com/jmoiron/sqlx"
"github.com/zenazn/goji/graceful"
"github.com/zenazn/goji/web"
)
type appContext struct {
db *sqlx.DB
store *sessions.CookieStore
templates map[string]*template.Template
}
// We need to define our custom handler type as a struct
type appHandler struct {
handler func(w http.ResponseWriter, r *http.Request) (int, error)
c *appContext
}
func (ah appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
status, err := ah.handler(w, r)
if err != nil {
log.Printf("HTTP %d: %q", status, err)
switch status {
case http.StatusNotFound:
// Would actually render a "http_404.tmpl" here...
http.NotFound(w, r)
case http.StatusInternalServerError:
// Would actually render a "http_500.tmpl" here
// (as above)
http.Error(w, http.StatusText(status), status)
default:
// Would actually render a "http_error.tmpl" here
// (as above)
http.Error(w, http.StatusText(status), status)
}
}
}
func main() {
// Both are 'nil' just for this example
context := &appContext{db: nil, store: nil}
r := web.New()
// A little ugly, but it works.
r.Get("/", appHandler{context.IndexHandler, context})
graceful.ListenAndServe(":8000", r)
}
func (app *appContext) IndexHandler(w http.ResponseWriter, r *http.Request) (int, error) {
fmt.Fprintf(w, "db is %q and store is %q", app.db, app.store)
return 200, nil
}
是否有更简洁的方式将context
实例传递给ServeHTTP
?
请注意go build -gcflags=-m
表明在堆分配的团队中这两个选项似乎都不是更糟糕的:&appContext
字面值在两种情况下都转移到堆(如预期的那样),尽管我的解释是结构基于选项确实会在每个请求上传递第二个指针(到context
) - 如果我在这里错误则纠正我,因为我希望能够更好地理解这一点。
我并不完全相信全局包在主包中是坏的(即不是lib)只要它们以这种方式安全使用(只读/互斥/池),但我确实希望明确地通过上下文提供。
答案 0 :(得分:6)
我会使用闭包并执行以下操作:
func IndexHandler(a *appContext) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *httpRequest) {
// ... do stuff
fmt.Fprintf(w, "db is %q and store is %q\n", a.db, a.store)
})
}
只需使用返回的http.Handler
。
您只需要确保appContext
是安全的。
答案 1 :(得分:4)
经过与一些有用的Gophers讨论#go-nuts之后,上面的方法是关于"尽可能好的"从我能辨别出来的。
ServeHTTP
也可以访问它。 请注意,我们无法将处理程序定义为appHandler
上的方法,即func (ah *appHandler) IndexHandler(...)
,因为我们需要在ServeHTTP
中调用处理程序(即ah.h(w,r)
)。
type appContext struct {
db *sqlx.DB
store *sessions.CookieStore
templates map[string]*template.Template
}
type appHandler struct {
handler func(w http.ResponseWriter, r *http.Request) (int, error)
*appContext // Embedded so we can just call app.db or app.store in our handlers.
}
// In main() ...
context := &appContext{db: nil, store: nil}
r.Get("/", appHandler{context.IndexHandler, context})
...
这也是,最重要的是,它与http.Handler
完全兼容,所以我们仍然可以使用通用中间件包装我们的处理程序结构,如:gzipHandler(appHandler{context.IndexHandler, context})
。
(我仍然对其他建议持开放态度!)
<强>更新强>
感谢this great reply on Reddit我找到了一个更好的解决方案,并不需要将每个请求传递给context
实例的两个引用。
我们只是创建一个接受嵌入式上下文和我们的处理程序类型的结构,并且由于http.Handler
,我们仍然满足ServeHTTP
接口。处理程序不再是我们的appContext
类型的方法,而只是接受它作为参数,这会导致稍微更长的函数签名,但仍然显而易见&#34;而且易于阅读。如果我们担心打字&#39;即使因为我们不再需要担心方法接收器,我们也要打破。
type appContext struct {
db *sqlx.DB
store *sessions.CookieStore
templates map[string]*template.Template
type appHandler struct {
*appContext
h func(a *appContext, w http.ResponseWriter, r *http.Request) (int, error)
}
func (ah appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// We can now access our context in here.
status, err := ah.h(ah.appContext, w, r)
log.Printf("Hello! DB: %v", ah.db)
if err != nil {
log.Printf("HTTP %d: %q", status, err)
switch status {
case http.StatusNotFound:
// err := ah.renderTemplate(w, "http_404.tmpl", nil)
http.NotFound(w, r)
case http.StatusInternalServerError:
// err := ah.renderTemplate(w, "http_500.tmpl", nil)
http.Error(w, http.StatusText(status), status)
default:
// err := ah.renderTemplate(w, "http_error.tmpl", nil)
http.Error(w, http.StatusText(status), status)
}
}
}
func main() {
context := &appContext{
db: nil,
store: nil,
templates: nil,
}
r := web.New()
// We pass a reference to context *once* per request, and it looks simpler
r.Get("/", appHandler{context, IndexHandler})
graceful.ListenAndServe(":8000", r)
}
func IndexHandler(a *appContext, w http.ResponseWriter, r *http.Request) (int, error) {
fmt.Fprintf(w, "db is %q and store is %q\n", a.db, a.store)
return 200, nil
}