dongqin5604 2017-05-22 10:42
浏览 15
已采纳

仅带有标准库的Golang中间件

My first stackoverflow question, so please go easy on my naivety about stackoverflow and the question asked, beginner in golang.

I would like to know the difference between the two calls and also simple understanding of the Handle, Handler, HandleFunc, HandlerFunc.

http.Handle("/profile", Logger(profilefunc))
http.HandleFunc("/", HomeFunc)

func main() {            
   fmt.Println("Starting the server.")

   profilefunc := http.HandlerFunc(ProfileFunc)

   http.Handle("/profile", Logger(profilefunc))
   http.HandleFunc("/", HomeFunc)

   http.ListenAndServe("0.0.0.0:8081", nil)
}

func Logger(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
        log.Println("Before serving request")
        h.ServeHTTP(w, r)
        log.Println("After serving request")
    })
}

func ProfileFunc(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "You are on the profile page.")
}

func HomeFunc(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello Imran Pochi")
}
  • 写回答

2条回答 默认 最新

  • dongliao6777 2017-05-22 13:52
    关注

    I would like ... simple understanding of the Handle, Handler, HandleFunc, HandlerFunc.

    • Handler is an interface that can respond to an HTTP request and has a ServeHTTP(ResponseWriter, *Request) method.
    • http.Handle registers a Handler to handle HTTP requests matching a given pattern.
    • http.HandleFunc registers a handler function to handle HTTP requests matching a given pattern. The handler function should be of the form func(ResponseWriter, *Request).
    • HandlerFunc is an explicit function type of the form func(ResponseWriter, *Request). HandlerFunc has a method ServeHTTP that calls itself . This allows you to cast a function to a HandlerFunc and use it as a Handler.

    I would to know the difference between the two calls

    http.Handle("/profile", Logger(profilefunc))
    http.HandleFunc("/", HomeFunc)
    

    Logger is an example of a middleware, which is a function that takes an http.Handler and it returns another http.Handler that wraps the original handler. When called this handler may (or may not) call the nested http.Handler before and/or after performing some operation. So the first line is saying register the profileFunc Handler wrapped in the Logger middleware with the pattern "/profile". The second line is saying register the HomeFunc function with the "/" pattern.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)