func examp(w http.ResponseWriter, req *http.Request){
text:="hi"
fmt.Fprintf(w,"%d
",text)
http.ServeFile(w, req, "./sample.csv")
}
I can not use http.servefile with fmt.Fprintf, always use first one. I was tryed w.Header().add but nothing changed. How can i fix it ?
http.ServeFile
adds Content-Type
and Content-Length
and writes the header. This must happen before you write to http.ResponseWriter
.
Your solution could be to avoid http.ServeFile
and write the file manually with io.Copy
:
func example(w http.ResponseWriter, req *http.Request) {
// Write some headers.
w.Header.Set("Content-Type", mime.TypeByExtension(filepath.Ext(name)))
// Write your content here.
fmt.Fprint(w, someContent)
// Write the file.
fileName := "sample.csv"
f, err := io.Open(fileName)
// check err
_, err = io.Copy(w, f)
// check err
}
The downside of io.Copy
is that it doesn't support Range requests (for resuming downloads, etc.)