Home > Article > Backend Development > How Can I Stream MP4 Videos in a Golang Web Server?
GoLang Web Server Streaming Video
Q: A Golang web server configured to serve HTML, CSS, JavaScript, and images unsuccessfully attempts to stream an MP4 video.
The issue arises from the handling of large video files. Chrome requires servers to support Range requests for videos exceeding a certain size, but the provided code does not address this. By implementing Range request support, the server can send only the requested portion of the video, enabling playback.
A: Enhance the code to support Range requests.
Modify the code to include a check for MP4 files and send appropriate headers and response codes:
<code class="go">if contentType == "video/mp4" { size := binary.Size(data) if size > 0 { requestedBytes := r.Header.Get("Range") w.Header().Add("Accept-Ranges", "bytes") w.Header().Add("Content-Length", strconv.Itoa(size)) w.Header().Add("Content-Range", "bytes "+requestedBytes[6:len(requestedBytes)]+strconv.Itoa(size-1)+"/"+strconv.Itoa(size)) w.WriteHeader(206) } }</code>
Additionally, consider using http.ServeFile() for serving the video files, which supports Range requests:
<code class="go">if contentType == "video/mp4" { http.ServeFile(w, r, path) }</code>
The above is the detailed content of How Can I Stream MP4 Videos in a Golang Web Server?. For more information, please follow other related articles on the PHP Chinese website!