gpt4 book ai didi

go - 在 martini.Context 中获取请求 url

转载 作者:数据小太阳 更新时间:2023-10-29 03:28:43 24 4
gpt4 key购买 nike

我想给自己发送电子邮件,但页面 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()
}

最佳答案

答案是将req *http.Request参数添加到func RecoverWrap(c martini.Context, req *http.Request, w http.ResponseWriter)/p>

完整代码:

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

关于go - 在 martini.Context 中获取请求 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28789901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com