英文:
How to modify golang request object?
问题
所以我一直在尝试使用中间件修改golang中的请求结构,我尝试创建一个自定义结构并嵌入请求对象和一些其他数据,但我无法将其类型断言为*http.Request,有人可以帮忙吗?提前谢谢。
编辑:这是我的结构的样子
type CustomRequest struct {
*http.Request
*profile.User // 这是我想嵌入到请求中的数据
}
// 然后我的中间件将是这样的
func Middleware(next http.HandlerFunc) http.HandlerFunc {
return http.HandleFunc(func (w http.ResponseWriter, r *http.Request)) {
user := &User{
// 用户详细信息在这里
}
customRequest := &CustomRequest{
r,
&user,
}
req := customRequest.(*http.Request)
next.ServeHttp(w, req)
}
英文:
So I've been trying to modify the request structure in golang using middleware, i tried creating a custom structure and embedding the request object and some more data but i can't type assert it to *http.Request, can anybody please help, thanks in advance.
Edit: so here is what my structure looks like
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)
}
答案1
得分: 4
这不是类型断言
的工作方式。
对于一个接口类型的表达式x和类型T,主表达式x.(T)断言x不是nil,并且存储在x中的值是类型T。x.(T)的表示法称为类型断言。
你可以对接口进行类型断言,得到它们的底层类型。
你不能将一个类型断言为另一个类型,那将是类型转换
,但在这种情况下,你不能在两者之间进行转换。你只能转换符合规范中描述的可转换的两种类型。
如果你想修改*http.Request
,直接进行修改即可,这些字段是可导出的。如果你想让请求携带额外的数据,可以将其以JSON格式写入请求体或URL中。
编辑:如果你想在程序中传递数据,你也可以使用上下文,但我不确定你具体在做什么。还有一个github.com/gorilla/context库可以使用。
英文:
That isn't how type assertion
works.
> For an expression x of interface type and a type T, the primary
> expression
>
> x.(T) asserts that x is not nil and that the value stored in x is of
> type T. The notation x.(T) is called a type assertion.
You type assert interfaces to their underlying type.
You can't type assert one type to another, that would be type conversion
, but in this case you can't convert between the two. You can only convert two types that are convertible according to the description in the spec above.
If you want to modify the *http.Request
just do it directly, the fields are exported. If you want the request to hold extra data just write it in the request body as JSON or in the url.
EDIT: For passing data around you can also use a context, but I am not sure of what you're doing. There is also github.com/gorilla/context
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论