gpt4 book ai didi

Gorilla mux 自定义中间件

转载 作者:IT老高 更新时间:2023-10-28 13:01:13 32 4
gpt4 key购买 nike

我正在使用 gorilla mux 来管理路由。我缺少的是在每个请求之间集成一个中间件。

例如

package main

import (
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
"strconv"
)

func HomeHandler(response http.ResponseWriter, request *http.Request) {

fmt.Fprintf(response, "Hello home")
}

func main() {

port := 3000
portstring := strconv.Itoa(port)

r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
http.Handle("/", r)

log.Print("Listening on port " + portstring + " ... ")
err := http.ListenAndServe(":"+portstring, nil)
if err != nil {
log.Fatal("ListenAndServe error: ", err)
}
}

每个传入的请求都应该通过中间件。如何在此处集成中间件?

更新

我会将它与 gorilla/sessions 结合使用,他们说:

Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory! An easy way to do this is to wrap the top-level mux when calling http.ListenAndServe:

如何防止这种情况发生?

最佳答案

只需创建一个包装器,在 Go 中相当容易:

func HomeHandler(response http.ResponseWriter, request *http.Request) {

fmt.Fprintf(response, "Hello home")
}

func Middleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("middleware", r.URL)
h.ServeHTTP(w, r)
})
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
http.Handle("/", Middleware(r))
}

关于Gorilla mux 自定义中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26204485/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com