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 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算