2017-07-18 26 views
0

我试图在我的项目中链处理程序。golang中间件

package main 

import (
    "database/sql" 
    "fmt" 
    "net/http" 
) 

func loggingHandler(next http.Handler) http.Handler { 
    fn := func(w http.ResponseWriter, r *http.Request) { 
     next.ServeHTTP(w, r) 
    } 
    return http.HandlerFunc(fn) 
} 

func loginHandler(res http.ResponseWriter, req *http.Request) { 
    if req.Method != "POST" { 
     http.ServeFile(res, req, "login.html") 
     return 
    } 
    // some code 
} 

func MainPageHandler(res http.ResponseWriter, req *http.Request) { 
    // some code 
} 

func main() { 
    db, err = sql.Open("", "[email protected]()/db name") 
    if err != nil { 
     fmt.Println(err) 
    } 
    defer db.Close() 
    commonHandlers := alice.New(loggingHandler) 
    http.Handle("/Login", commonHandlers.ThenFunc(loginHandler)) 
    http.Handle("/", commonHandlers.ThenFunc(MainPageHandler)) 
    http.ListenAndServe(":8080", nil) 
} 

我该怎么做才能得到输出? 在此先感谢。

+0

这已经做过很多次的去了。如果你想要一些轻巧的东西,并附带一些“电池”,请浏览https://github.com/urfave/negroni,它非常流行,易于使用。记录和从恐慌中恢复是标准的。 – reticentroot

+0

从panics中恢复已经是'net/http'中的标准。 – Adrian

+0

@尝试发布至少会编译的代码(除非您发布有关编译问题)。引用的代码引用了未定义或导入的“alice”。 – Adrian

回答

0

通过传递http.ResponseWriter作为第一个参数,请求处理程序可以使用任何fmtFprint* methods来编写响应。

例如:

func handler(w http.ResponseWriter, r *http.Request) { 
    fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path) 
}