3 ms·
You can use closures: func SomeHandler(foo Foo) { return func(w http.ResponseWriter, req *http.Request) { // use foo } } // later, during init
by acrispino 13y ago
You can use closures:
func SomeHandler(foo Foo) {
return func(w http.ResponseWriter, req *http.Request) {
// use foo
}
}
// later, during init
http.HandleFunc("/foo", SomeHandler(someFoo))
or method values, introduced in go 1.1:
type handler struct {
foo Foo
}
func (h *handler) bar(w http.ResponseWriter, req *http.Request) {
// use h.foo
}
func (h *handler) qux(w http.ResponseWriter, req *http.Request) {
// use h.foo
}
// later
h := handler{
foo: someFoo,
}
http.HandleFunc("/bar", h.bar)
http.HandleFunc("/qux", h.qux)
- BarkMore 13y agoThe GP's comment is about request context, not handler context.