sçuçu
sçuçu

Reputation: 3070

Writing Both session and JSON data to http.ResponseWriter

Is it possible to send both session and some custom app specific json data to the client form net/http package of Go.

I am using gorilla/sessions for session. And after storing values, needs to call func (s *CookieStore) Save(r *http.Request, w http.ResponseWriter, session *Session) error.

But on the other hand this handler function also needs to send some JSON data to the client by fmt.Fprintf(http.ResponseWriter, string(js)).

How can this be achieved?

Upvotes: 2

Views: 1396

Answers (2)

OneOfOne
OneOfOne

Reputation: 99361

Seasons in general are stored as cookies, so it is sent as a header, you need to save it first then write your json data.

Also you should look into using json.Encoder instead of json.Marshal.

func handler(w http.ResponseWriter, r *http.Request) {
    session, _ := store.Get(r, "session")
    // stuff with session
    session.Save(r, w)
    w.Header().Set("Content-Type", "application/json")
    enc := json.NewEncoder(w)
    if err := enc.Encode(somedatastruct{}); err != nil {
        //handle err
    }
}

Upvotes: 1

Simon Fox
Simon Fox

Reputation: 6425

Yes, you can write both. The cookie associated with the session is written to the response header. The JSON data is written to the response body. Just be sure to save the session first as changes to the response headers are ignored once the application starts to write the response body.

Assuming that r is the *http.Request, w is the http.ResponseWriter and d is a []byte containing the JSON, then you should:

session.Save(r, w)
w.Write(d)

If you are using the standard encoding/json package, then you can encode directly to the response body. Also, you should set the content type.

session.Save(r, w)
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(yourData); err != nil {
   // handle error
}

Upvotes: 0

Related Questions