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

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:])
}
dongsuoxi1790
dongsuoxi1790 相关:stackoverflow.com/q/53231492/13860
一年多之前 回复
dqegbo2691
dqegbo2691 如果您想与动态值(名称,密码)一起提供html(/html/home.html),则可能要考虑使用模板。
一年多之前 回复
doushan1850
doushan1850 您最多只能发送一个回复。发送多个独立的东西通常是由多部分响应完成的(例如,当您提交带有文件输入的HTML表单时,与请求相同的事情)。
一年多之前 回复

3个回答

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.



发送用户名和密码是一种响应,提供文件也是一种响应。 您不能一次发送两个单独的响应。您可以发送一个对象作为响应,其中包含用户名密码和服务器中文件的URL。</ p>
</ div>

展开原文

原文

sending username and password is a response , serving a file is a response too. You can't send two separate response at once.You can send an object as response containing username password and url of the file in the server.



您只发送了一个响应,但是我们可以将多部分响应以某种模式组合在一起。</ p>

< p>例如:</ p>

  {
“用户名”:“ xxxx”,
“密码”:“ xxxx”,
“文件”:“文件uri”

}

</ code> </ pre>
</ div>

展开原文

原文

You just send only one response, but we can combine multipart responses in one with some pattern.

Like this:

{
  "username": "xxxx",
  "password": "xxxx",
  "file": "file uri"
}

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐