所以我一直在尝试使用中间件修改golang中的请求结构,我尝试创建自定义结构并嵌入请求对象和更多数据,但我无法将其声明为* http。请求,任何人都可以提前帮助,谢谢。
编辑:所以这就是我的结构的样子
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)
}
答案 0 :(得分:1)
这不是type assertion
的工作方式。
对于接口类型的表达式x和类型T,表示主要的 表达
x。(T)断言x不是nil,而x中存储的值是 类型T.符号x。(T)称为类型断言。
您键入断言接口到其基础类型。
您不能键入一种类型断言另一种类型,即type conversion
,但在这种情况下,您无法在两者之间进行转换。您只能根据上面的规范转换两种可转换的类型。
如果您想直接修改*http.Request
,则会导出字段。如果您希望请求保存额外数据,只需将其作为JSON或在URL中写入请求正文中。
编辑:为了传递数据,你也可以use a context,但我不确定你在做什么。还有github.com/gorilla/context