Skip to content

Instantly share code, notes, and snippets.

@yakuter
Created February 15, 2024 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yakuter/87dacd9e39a7a8f2681bd6c3d33684bf to your computer and use it in GitHub Desktop.
Save yakuter/87dacd9e39a7a8f2681bd6c3d33684bf to your computer and use it in GitHub Desktop.
Copy and Movement 7
package main
import (
"io"
"net/http"
"os"
)
func main() {
http.HandleFunc("/download", func(w http.ResponseWriter, r *http.Request) {
filePath := "largeFile.txt"
file, err := os.Open(filePath)
if err != nil {
http.Error(w, "File not found", http.StatusNotFound)
return
}
defer file.Close()
// Stream the file content to the client
// Set headers
w.Header().Set("Content-Disposition", "attachment; filename="+filePath)
w.Header().Set("Content-Type", "application/octet-stream")
// Copy the file to the HTTP response
_, err = io.Copy(w, file)
if err != nil {
http.Error(w, "Error streaming file", http.StatusInternalServerError)
}
})
println("Server listening on port 8080...")
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment