【问题标题】:get request url in martini.Context在 martini.Context 中获取请求 url
【发布时间】:2015-03-01 03:52:19
【问题描述】:

我想向自己发送电子邮件,但在页面 http://localhost:3000/panic 上出现错误,其中包含错误 url - 在我们的例子中是 /panic。但我不知道如何在RecoverWrap 方法中从c martini.Context 获取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()
}

【问题讨论】:

    标签: go martini


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2011-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多