Skip to content

Instantly share code, notes, and snippets.

@sunjayaali
Created May 20, 2019 18:06
Show Gist options
  • Save sunjayaali/7a5b4596c97359a307dd4fa0c1faa7da to your computer and use it in GitHub Desktop.
Save sunjayaali/7a5b4596c97359a307dd4fa0c1faa7da to your computer and use it in GitHub Desktop.
Example to read a file and send it to browser with Go.
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
)
func internalServerError(w http.ResponseWriter, err error) {
log.Println(err)
status := http.StatusInternalServerError
w.WriteHeader(status)
json.NewEncoder(w).Encode(map[string]interface{}{
"status": status,
"error": err,
})
}
func handleDownload(w http.ResponseWriter, r *http.Request) {
file := "hello.txt" //your file, it can be relative path in your working dir
filePath, err := filepath.Abs(file)
if err != nil {
internalServerError(w, err)
return
}
f, err := os.Open(filePath)
if err != nil {
internalServerError(w, err)
return
}
defer f.Close()
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", file))
io.Copy(w, f)
}
func main() {
http.HandleFunc("/", handleDownload)
http.ListenAndServe(":3000", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment