doujiao7325 2019-06-14 06:53
浏览 226
已采纳

如何为一个请求发送两个响应?

I have a HTTP server in Go in which when client is asking for any file I am serving it using http.ServeFile. I need to send username and password with this file also. For that I am doing it by first sending a response with fmt.Fprintf and later I am doing http.ServeFile. So it is solving the purpose but it is throwing a warning "http: superfluous response.WriteHeader call". How to resolve this.

Please Note: I need to send username and password with the served file.

if r.URL.Path == "/html/home.html" {
   fmt.Fprintf(w, `<!DOCTYPE HTML>
        <html><div><input id="username" type="hidden" readonly value="%s" /> 
        <br><input id="password" type="hidden" readonly value="%s" /><div>`, 
        name, password)
   http.ServeFile(w, r, r.URL.Path[1:])
}
  • 写回答

3条回答

  • douwen1549 2019-08-16 06:28
    关注

    ERROR:= "http: superfluous response.WriteHeader call". This error is coming as you cannot send two response for one request.

    The best way to achieve what you are trying to do is by using cookies. Send the data in the form of cookies and Bingo. Your work will be done without errors/warnings.

    expiration := time.Now().Add(time.Second * time.Duration(1000))
    cookie := http.Cookie{Name: "Token", Value: "username", Expires: expiration}
    http.SetCookie(w, &cookie)
    usercookie := http.Cookie{Name: "usercookie", Value: "username", Expires: expiration}
    http.SetCookie(w, &usercookie)
    http.ServeFile(w, r, r.URL.Path[1:])
    

    This Code will create a cookie and later you can access it. This is the right way of achieving what you want.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable