Created
February 15, 2024 17:25
-
-
Save yakuter/87dacd9e39a7a8f2681bd6c3d33684bf to your computer and use it in GitHub Desktop.
Copy and Movement 7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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