Skip to content

Instantly share code, notes, and snippets.

@spkellydev
Last active March 13, 2019 06:37
Show Gist options
  • Save spkellydev/d04b4b8457d2db81d1c489a1c10afe83 to your computer and use it in GitHub Desktop.
Save spkellydev/d04b4b8457d2db81d1c489a1c10afe83 to your computer and use it in GitHub Desktop.
Simple go script to handle downloading files
package main
import (
"net/http"
"log"
"os"
"io"
"strconv"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
Filename := request.URL.Query().Get("file")
OpenFile, err := os.Open(FileName)
if err != nil {
http.Error(w, "no file", 404)
}
FileHeader := make([]byte, 1024)
OpenFile.Read(FileHeader)
FileContentType := http.DetectContentType(FileHeader)
FileStat, _ := OpenFile.Stat()
FileSize := strconv.FormatInt(FileStat.Size(), 10)
w.Header().Set("Content-Disposition", "attachment; filename=" + FileName)
w.Header().Set("Content-Type", FileContentType)
w.Header().Set("Content-Length", FileSize)
OpenFile.Seek(0, 0)
io.Copy(w, OpenFile)
return
});
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment