A webserver developed using GoLang displays static content (HTML, JavaScript, CSS, and images) successfully. However, when attempting to display an MP4 video, the browser cannot load it.
The issue arises from the size of the video file. Chrome buffers the content, but only partially for large videos. When the video exceeds a certain threshold, Chrome expects the server to support partial content serving (Range requests).
In the provided code, the custom file serving implementation does not handle Range requests, leading to Chrome refusing to play the video.
To resolve the issue, use http.ServeFile() to serve the video files. http.ServeFile() automatically handles Range requests and sets appropriate response headers, including the Content-Type and Accept-Ranges: bytes headers necessary for Chrome to play the video.
Modify the provided code as follows:
<code class="go">func (vh *viewHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { path := r.URL.Path[1:] log.Println(path) if contentType == "video/mp4" { http.ServeFile(w, r, path) } else { data, err := ioutil.ReadFile(string(path)) if err == nil { w.Header().Add("Content-Type", contentType) w.Write(data) } else { log.Println("ERROR!") w.WriteHeader(404) w.Write([]byte("404 - " + http.StatusText(404))) } } }</code>
This implementation will correctly serve MP4 videos, ensuring they can be played in Chrome.
The above is the detailed content of Why can\'t my GoLang webserver play MP4 videos in Chrome?. For more information, please follow other related articles on the PHP Chinese website!