英文:
Add middleware on HTTP
问题
我有这个productHandler:
func productHandler(w http.ResponseWriter, r *http.Request) {
var prop controller.Product
switch r.Method {
case "GET":
prop.All()
} [etc..]
}
然后我注册了我的productHandler:
http.HandleFunc("/products/", productHandler)
如何将下面的中间件添加到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)
}
如何将这个中间件添加到所有的处理程序中?
我尝试过:
type Pr struct {
handler http.Handler
}
func (p *Pr) ServeHttp(w http.ResponseWriter, r *http.Request) {
p.handler.ServeHTTP(w, r)
w.Write([]byte("Test M"))
}
我正在尝试在应用程序引擎SDK上实现这个,但是没有成功。
英文:
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.
答案1
得分: 1
尝试使用http.Handle("/products/", Accept(http.HandlerFunc(productHandler)))
进行处理。
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)))
}
你可以在这里查看代码:http://play.golang.org/p/mvclC4UUMV
英文:
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)))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论