为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
函数式编程 2023-02-06 19:31:36
我正在使用以下代码: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")))谢谢
查看完整描述

2 回答

?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

您的应用程序的处理程序是http.DefaultServeMux。用另一个执行代码的处理程序包装该处理程序:


// wrap returns an http.Handler that wraps another http.Handler

func 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 中注册一个处理程序。创建自己的多路复用器可确保您完全控制应用程序中运行的处理程序。


查看完整回答
反对 回复 2023-02-06
?
冉冉说

TA贡献1877条经验 获得超1个赞

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))


查看完整回答
反对 回复 2023-02-06
  • 2 回答
  • 0 关注
  • 56 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信