Created
January 15, 2024 14:09
-
-
Save AnjanaMadu/7d98397329d089e7f4452898ebbe7763 to your computer and use it in GitHub Desktop.
Go code to stream file to client which hasn't completed
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 ( | |
"net/http" | |
"os" | |
"time" | |
) | |
// function to generate file in 10 seconds | |
func generateFile(done chan bool) { | |
f, _ := os.OpenFile("example.txt", os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644) | |
defer f.Close() | |
for i := 0; i < 10; i++ { | |
f.WriteString(time.Now().String() + "\n") | |
time.Sleep(1 * time.Second) | |
} | |
done <- true | |
} | |
func main() { | |
os.Remove("example.txt") | |
http.HandleFunc("/", downloadHandler) | |
http.ListenAndServe(":8080", nil) | |
} | |
func downloadHandler(w http.ResponseWriter, r *http.Request) { | |
// Set the appropriate headers for file download | |
w.Header().Set("Content-Disposition", "attachment; filename=example.txt") | |
w.Header().Set("Content-Type", "application/octet-stream") | |
done := make(chan bool) | |
lastByteRead := 0 | |
go generateFile(done) | |
time.Sleep(1 * time.Second) // wait for file to be created | |
f, _ := os.Open("example.txt") | |
defer f.Close() | |
for { | |
select { | |
case <-done: | |
return | |
default: | |
// read file in chunks of 1024 bytes | |
f.Seek(int64(lastByteRead), 0) | |
buf := make([]byte, 1024) | |
n, err := f.Read(buf) | |
if err != nil && err.Error() == "EOF" { | |
return | |
} | |
w.Write(buf[:n]) | |
w.(http.Flusher).Flush() | |
lastByteRead += int(n) | |
time.Sleep(1 * time.Second) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment