I'm trying to use ServeContent to serve files (which may be large movie files, so it will use byte ranges), but I'm not sure how to handle the modified time. If I use the following program to serve a movie, it fails if I give the actual modified time of the file as shown. I think what happens is that the first request works, but subsequent ones (of different byte ranges of the file) think it already has the file and therefore they fail and the movie doesn't play. Is there something I am doing wrong?
Note that the code works (and the movie plays properly) if I use time.Now() instead of the actual modified time of the file, but that isn't correct of course.
package main
import (
"fmt"
"net/http"
"os"
"path"
"time"
)
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":3000", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
filePath := "." + r.URL.Path
file, err := os.Open(filePath)
if err != nil {
fmt.Printf("%s not found
", filePath)
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "<html><body style='font-size:100px'>four-oh-four</body></html>")
return
}
defer file.Close()
fileStat, err := os.Stat(filePath)
if err != nil {
fmt.Println(err)
}
fmt.Printf("serve %s
", filePath)
_, filename := path.Split(filePath)
t := fileStat.ModTime()
fmt.Printf("time %+v
", t)
http.ServeContent(w, r, filename, t, file)
}