在martini.Context中获取请求URL

时间:2015-03-01 03:52:19

标签: go martini

我想向自己发送电子邮件,但在http://localhost:3000/panic页面上发生了错误,其中包含错误网址 - /panic。但我无法弄清楚如何从c martini.Context方法RecoverWrap中获取网址。

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()
}

1 个答案:

答案 0 :(得分:0)

答案是将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()
}