0

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)
}
3
  • Please show us your code (the embedder struct). Commented Sep 9, 2015 at 5:25
  • You should be able to modify the *http.Request directly, the fields are exported. Commented Sep 9, 2015 at 5:25
  • which line and error message please. Commented Sep 9, 2015 at 7:03

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.