繁体   English   中英

如何修改golang请求对象?

[英]How to modify golang request object?

所以我一直在尝试使用中间件修改 golang 中的请求结构,我尝试创建一个自定义结构并嵌入请求对象和一些更多数据,但我无法将其输入到 *http.Request 中,任何人都可以帮忙,提前致谢。

编辑:所以这是我的结构的样子

type CustomRequest struct {
    *http.Request
    *profile.User // This is the data i want to embed into the request
}

// then my middlware will be something like

func Middleware(next http.HandlerFunc) http.HandlerFunc {
    return http.HandleFunc(func (w http.ResponseWriter, r *http.Request)) {
        user := &User{
        // User Details Are Here
        }

        customRequest := &CustomRequest{
            r,
            &user,
        }

        req := customRequest.(*http.Request)

        next.ServeHttp(w, req)
}

这不是type assertion工作方式。

对于接口类型的表达式 x 和类型 T,主要表达式

x.(T) 断言 x 不是 nil 并且存储在 x 中的值是 T 类型。符号 x.(T) 称为类型断言。

您将断言接口键入其基础类型。

您不能将一种类型断言为另一种类型,即type conversion ,但在这种情况下,您无法在两者之间进行转换。 根据上述规范中的描述,您只能转换两种可转换的类型。

如果你想修改*http.Request直接做,字段被导出。 如果您希望请求包含额外的数据,只需将其作为 JSON 或 url 写入请求正文中。

编辑:为了传递数据,你也可以使用 context ,但我不确定你在做什么。 还有github.com/gorilla/context

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM