Echo: Setting Response Headers in handlers

Created on 15 Jul 2015  Â·  2Comments  Â·  Source: labstack/echo

Little confused about setting response headers with c.Context. The following:

func main() {
    e := echo.New()

    tokenize := func(c *echo.Context) error {
            c.Response.Header().Set("Authorization", "Bearer " + "eyJhbGciOiJSU0E…")
            c.Response.WriteHeader(201)
            return c.JSON(http.StatusCreated, "Tokenized")
    }

    e.Post("/secure", tokenize)

    e.Run(":8000")
}

gives me, not unpredictably:

c.Response.Header undefined (type func() *echo.Response has no field or method Header) 
c.Response.WriteHeader undefined (type func() *echo.Response has no field or method WriteHeader)

With a (w http.ResponseWriter, r *http.Request), this would work:

w.Header().Set("Authorization", "Bearer " + "eyJhbGciOiJSU0E…")
w.WriteHeader(http.StatusCreated)
fmt.Fprintln(w, "Tokenized")

What is the best way to set headers with _echo_ in this context?

Most helpful comment

Sorry, very tired. Forgot it's c.Response() and not c.Response, as in :

c.Response().Header().Set("Authorization", "Bearer " + "eyJhbGciOiJSU0E…")
c.Response().WriteHeader(201)

Solved, thanks.

All 2 comments

Sorry, very tired. Forgot it's c.Response() and not c.Response, as in :

c.Response().Header().Set("Authorization", "Bearer " + "eyJhbGciOiJSU0E…")
c.Response().WriteHeader(201)

Solved, thanks.

@pandex Jesus, I copied the code of your first comment, and I made the same mistake, it wasted my 20 minutes.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ellisonleao picture ellisonleao  Â·  3Comments

mmindenhall picture mmindenhall  Â·  4Comments

arun0009 picture arun0009  Â·  3Comments

alexzorin picture alexzorin  Â·  3Comments

dre1080 picture dre1080  Â·  4Comments