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 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services