2
votes

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?

2
Should I find another way to notify the client of login case, by which I make client side code to decide which template to render. Like gathering the cookie storage from the browser on client-side, which I do not know how to at the moment?sçuçu
I think you can, but I'm not familiar enough with the specific packages to write up a full answer. You might have to set the cookie/session data first, since headers like Set-Cookie get flushed out before Writes.twotwotwo

2 Answers

1
votes

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
    }
}
0
votes

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
}