dook0034
2014-09-30 23:28 阅读 150

将会话和JSON数据都写入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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    doukengsha9472 doukengsha9472 2014-09-30 23:37

    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
    }
    
    点赞 评论 复制链接分享
  • douketangyouzh5219 douketangyouzh5219 2014-09-30 23:40

    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
        }
    }
    
    点赞 评论 复制链接分享