Home > Backend Development > Golang > How Can I Stream MP4 Videos in a Golang Web Server?

How Can I Stream MP4 Videos in a Golang Web Server?

Barbara Streisand
Release: 2024-11-02 15:01:02
Original
1076 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template