Go 获取martini.Context中的请求url
我想向自己发送电子邮件,在本例中,页面上出现错误,包含错误url-Go 获取martini.Context中的请求url,go,martini,Go,Martini,我想向自己发送电子邮件,在本例中,页面上出现错误,包含错误url-/panic。但我不知道如何从c martini.ContextinsideRecoverWrap方法中获取url package main import ( "errors" "github.com/go-martini/martini" "net/http" ) func main() { m := martini.Classic() m.Use(RecoverWrap) m
/panic
。但我不知道如何从c martini.Context
insideRecoverWrap
方法中获取url
package main
import (
"errors"
"github.com/go-martini/martini"
"net/http"
)
func main() {
m := martini.Classic()
m.Use(RecoverWrap)
m.Get("/panic", func() {
panic("some panic")
})
m.Get("/", func(req *http.Request, res http.ResponseWriter) {
res.Write([]byte("mainPage"))
})
m.Run()
}
func RecoverWrap(c martini.Context, w http.ResponseWriter) {
var err error
defer func(w http.ResponseWriter) {
r := recover()
if r != nil {
switch t := r.(type) {
case string:
err = errors.New(t)
case error:
err = t
default:
err = errors.New("Unknown error")
}
// how to get request url here
// I want to send email with error url
http.Error(w, "Something goes wrong", http.StatusInternalServerError)
}
}(w)
c.Next()
}
答案是将
req*http.Request
参数添加到func RecoverWrap(c martini.Context,req*http.Request,w http.ResponseWriter)
完整代码:
package main
import (
"errors"
"fmt"
"github.com/go-martini/martini"
"net/http"
)
func main() {
m := martini.Classic()
m.Use(RecoverWrap)
m.Get("/panic", func() {
panic("some panic")
})
m.Get("/", func(req *http.Request, res http.ResponseWriter) {
res.Write([]byte("mainPage"))
})
m.Run()
}
func RecoverWrap(c martini.Context, req *http.Request, w http.ResponseWriter) {
var err error
defer func(w http.ResponseWriter) {
r := recover()
if r != nil {
switch t := r.(type) {
case string:
err = errors.New(t)
case error:
err = t
default:
err = errors.New("Unknown error")
}
fmt.Println("req.URL.Path")
fmt.Println(req.URL.Path)
http.Error(w, "Something goes wrong", http.StatusInternalServerError)
}
}(w)
c.Next()
}