douzhan3900 2015-10-10 11:15
浏览 11
已采纳

如何为Go中的所有请求创建通用功能?

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条回答 默认 最新

  • 普通网友 2015-10-10 15:22
    关注

    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))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害