dook0034 2014-09-30 23:28
浏览 454
已采纳

将会话和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 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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺