How to create a common function for all requests in Go?

huangapple go评论95阅读模式
英文:

How to create a common function for all requests in Go?

问题

我正在使用Go编写一个Web应用程序,以提高对它的熟悉程度。我的用例非常简单。我想要一个通用函数,该函数将在每个请求中执行,并根据用户状态生成导航栏。

init方法如下(也会给你一个关于处理程序方法实现的想法):

func init() {
    initDB()
    gob.Register(user.User{})
    r := mux.NewRouter()
    r.HandleFunc("/", handleHome)
    http.Handle("/", r)
}

我正在使用以下方法执行模板:

func executeTemplate(w http.ResponseWriter, name string, status int, data map[string]interface{}) error {
    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    w.WriteHeader(status)
    data["User"] = getUser(r)
    return tpls[name].ExecuteTemplate(w, "base", data)
}

我正在使用Gorilla工具包存储会话,但据我了解,我每次都需要http.Request实例才能访问cookie存储。现在,我不想更改executeTemplate方法的签名。有没有办法在不更改任何现有方法的签名的情况下添加一个生成导航栏的函数?

有哪些好的方法可以实现这一点(即使需要更改现有方法的签名)?

英文:

I am writing a web application with Go to get better with it. My use case is pretty simple. I want to have a common function that will be executed for every request and will generate the navigation bar depending on the user status.

init method looks like (will also give you the idea of my implementation of handler methods):

func init() {
	initDB()
	gob.Register(user.User{})
	r := mux.NewRouter()
	r.HandleFunc("/", handleHome)
    http.Handle("/", r)
}

I am using the following method to execute templates.

func executeTemplate(w http.ResponseWriter, name string, status int, data map[string]interface{}) error {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.WriteHeader(status)
	data["User"] = getUser(r)
	return tpls[name].ExecuteTemplate(w, "base", data)
}

I am using Gorilla toolkit to store the session but as of my understanding, I need the http.Request instance every time to access the cookie store. Now I don't want to change the signature of executeTemplate method. Is there any way I can add a function to generate the navigation bar without changing signature of any of the existing methods?

What are some good ways to do it (even with changing the existing methods)?

答案1

得分: 3

在Gorillatoolkit中创建中间件的基本常见方法是包装顶级mux。类似于以下代码:

func Middleware(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // 在这里使用请求进行一些操作
        h.ServeHTTP(w, r)
    })
}

然后

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

这段代码的作用是创建一个中间件函数Middleware,它接受一个http.Handler作为参数,并返回一个新的http.Handler。在中间件函数中,你可以对请求进行一些操作,然后调用传入的处理函数h.ServeHTTP(w, r)来处理请求。在主函数中,你可以使用mux.NewRouter()创建一个新的路由器,然后使用r.HandleFunc()来注册处理函数,最后使用http.Handle()将中间件应用到路由器上。

英文:

Basic common approach to create middleware in Gorillatoolkit is to wrap top-level mux. Something like

func Middleware(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        //You do something here using request
        h.ServeHTTP(w, r)
    })
}

And then

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

huangapple
  • 本文由 发表于 2015年10月10日 19:15:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/33053361.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定