"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Stream MP4 Videos in a Golang Web Server?

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

Published on 2024-11-14
Browse:602

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:

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)
    }
}

Additionally, consider using http.ServeFile() for serving the video files, which supports Range requests:

if contentType == "video/mp4" {
    http.ServeFile(w, r, path)
}
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3