9

I'm using Go's built in http server and pat to respond to some URLs:

mux.Get("/products", http.HandlerFunc(index))

func index(w http.ResponseWriter, r *http.Request) {
    // Do something.
}

I need to pass in an extra parameter to this handler function - an interface.

func (api Api) Attach(resourceManager interface{}, route string) {
    // Apply typical REST actions to Mux.
    // ie: Product - to /products
    mux.Get(route, http.HandlerFunc(index(resourceManager)))

    // ie: Product ID: 1 - to /products/1
    mux.Get(route+"/:id", http.HandlerFunc(show(resourceManager)))
}

func index(w http.ResponseWriter, r *http.Request, resourceManager interface{}) {
    managerType := string(reflect.TypeOf(resourceManager).String())
    w.Write([]byte(fmt.Sprintf("%v", managerType)))
}

func show(w http.ResponseWriter, r *http.Request, resourceManager interface{}) {
    managerType := string(reflect.TypeOf(resourceManager).String())
    w.Write([]byte(fmt.Sprintf("%v", managerType)))
}

How can I send in an extra paramter to the handler function?

2 Answers 2

16

You should be able to do what you wish by using closures.

Change func index() to the following (untested):

func index(resourceManager interface{}) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        managerType := string(reflect.TypeOf(resourceManager).String())
        w.Write([]byte(fmt.Sprintf("%v", managerType)))
    }
}

And then do the same to func show()

3
  • 1
    Hehe, yes, I saw that you had the exact same code in your own conclusion.
    – ANisus
    May 21, 2014 at 3:48
  • 1
    An alternative signature: func index(rm interface{}) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ... } }
    – elithrar
    May 21, 2014 at 4:03
  • 1
    That signature is nicer, and it removes the need for http.HandlerFunc in the Attach() function. I'll update my answer.
    – ANisus
    May 21, 2014 at 4:19
8

Another option is to use types implementing http.Handler directly rather than only using functions. For example:

type IndexHandler struct {
    resourceManager interface{}
}

func (ih IndexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    managerType := string(reflect.TypeOf(ih.resourceManager).String())
    w.Write([]byte(fmt.Sprintf("%v", managerType)))
}

...
mux.Get(route, IndexHandler{resourceManager})

This kind of pattern can be useful if you want to refactor your ServeHTTP handler method into multiple methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.