每次有人进入我的网站时如何运行特定功能?

我正在使用以下代码:


func main() {


    http.Handle("/", http.FileServer(http.Dir("./web-files")))


    http.HandleFunc("/auth/verify", verify)

    http.HandleFunc("/auth/login", login)

    http.HandleFunc("/auth/signup", signup)


    http.ListenAndServe(":8080", nil)

}

我是新手,我想做的是每次有人进入我的网页时,都会运行一个名为updateCookiesruns 的函数。我尝试使用http.HandleFunc("/", updateCookies)但没有用,因为我已经使用过http.Handle("/", http.FileServer(http.Dir("./web-files")))


谢谢


函数式编程
浏览 57回答 2
2回答

鸿蒙传说

您的应用程序的处理程序是http.DefaultServeMux。用另一个执行代码的处理程序包装该处理程序:// wrap returns an http.Handler that wraps another http.Handlerfunc wrap(h http.Handler) http.HandlerFunc {    return func(w http.ResponseWriter, r *http.Request) {        // Before hook.        updateCookies(w, r)        h.ServeHTTP(w, r)  // call the wrapped handler        // After hook.        // Nothing for now.    }}func main() {    http.Handle("/", http.FileServer(http.Dir("./web-files")))    http.HandleFunc("/auth/verify", verify)    http.HandleFunc("/auth/login", login)        http.HandleFunc("/auth/signup", signup)    http.ListenAndServe(":8080", wrap(http.DefaultServeMux))}我编写代码来包装任意处理程序,因为可以轻松过渡到使用您自己的http.ServeMux:func main() {    mux := http.NewServeMux()    mux.Handle("/", http.FileServer(http.Dir("./web-files")))    mux.HandleFunc("/auth/verify", verify)    mux.HandleFunc("/auth/login", login)    mux.HandleFunc("/auth/signup", signup)    http.ListenAndServe(":8080", wrap(mux))}任何包都可以在 http.DefaultServeMux 中注册一个处理程序。创建自己的多路复用器可确保您完全控制应用程序中运行的处理程序。

冉冉说

http.Handle, http.HandleFunc, 和http.ListenAndServe(nil作为第二个参数),http.DefaultServeMux用于将请求路由到它们各自的处理程序。http.ListenAndServe仅当传递给它的第二个参数是时才使用默认 mux nil。如果提供了非 nil 参数,那么它将使用该参数而不是默认的 mux 来处理传入的请求。鉴于http.ListenAndServe第二个参数的类型是http.Handler接口,您可以简单地将updateCookiestohttp.ListenAndServe作为第二个参数传递(尽管您必须将其显式转换为http.HandlerFunc),然后修改updateCookies为,最后将 thew和 the传递r给默认多路复用器。func updateCookies(w http.ResponseWriter, r *http.Request) {    // ... [your original cookie code] ...    http.DefaultServeMux.ServeHTTP(w, r)}// ...http.ListenAndServe(":8080", http.HandlerFunc(updateCookies))
打开App,查看更多内容
随时随地看视频慕课网APP