Reputation: 634
I have this productHandler:
func productHandler(w http.ResponseWriter, r *http.Request) {
var prop controller.Product
switch r.Method {
case "GET":
prop.All()
} [etc..]
}
Then I register my productHandler
http.HandleFunc("/products/", productHandler)
How can I add the below middleware to HTTP request?
func Accept(next http.Handler) http.Handler {
fc := func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Accept") != "application/json" {
w.Write([]byte("Test M."))
return
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fc)
}
How can I add this middleware to all my handlers?
I have tried:
type Pr struct {
handler http.Handler
}
func (p *Pr) ServeHttp(w http.ResponseWriter, r *http.Request) {
a.handler.ServeHTTP(w, r)
w.Write([]byte("Test M"))
}
I am trying to implement this on the app engine SDK.
But it din't work.
Upvotes: 0
Views: 152
Reputation: 48330
Try http.Handle("/products/", Accept(http.HandlerFunc(productHandler)))
http://play.golang.org/p/mvclC4UUMV
package main
import (
"fmt"
"net/http"
)
func Accept(next http.Handler) http.Handler {
fc := func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Accept") != "application/json" {
w.Write([]byte("Test M."))
return
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fc)
}
func productHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
}
}
func main() {
http.Handle("/products/", Accept(http.HandlerFunc(productHandler)))
}
Upvotes: 1