2

I was wondering what's the best way to stream a video file (mpg4/avi - or any other format) in Go. Possibly, I'd like to be able to play it using a simple tag.

I've tried playing the famous Big Buck Bunny file with this code:

package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
    "time"
)

func serveHTTP(w http.ResponseWriter, r *http.Request) {
    video, err := os.Open("./bunny.avi")
    if err != nil {
        log.Fatal(err)
    }
    http.ServeContent(w, r, "bunny.avi", time.Now(), video)
    defer video.Close()
}

func main() {
    http.HandleFunc("/", serveHTTP)
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Println(err.Error())
    }
}

But when loading the html page in my browser nothing plays and only one http request is actually triggered and only one response with 206 Partial content is sent to the page. Response

The html page contains the following code in the body:

<video width="320" height="240" controls autoplay>
    <source src="http://localhost:8080">
    Your browser does not support the video tag.
</video>

Thank you!

Sync
  • 227
  • 4
  • 12
  • Possible duplicate of [How to serve http partial content with Go?](https://stackoverflow.com/questions/36540610/how-to-serve-http-partial-content-with-go/36543480#36543480) – icza Dec 09 '17 at 07:58

2 Answers2

2

Your go code looks fine, leading me to think this is probably a problem with your video. avi is usually not supported for html5, see here for more details on containers/codecs for html5.

I would try with a known working video. eg: https://www.quirksmode.org/html5/videos/big_buck_bunny.mp4

Maybe even simplify your code and just use http.ServeFile, although the important part of video serving (range requests) is in ServeContent anyway.

Marc
  • 19,394
  • 6
  • 47
  • 51
  • Thanks Marc you're right it was a problem with the video! Using ServeContent is extremely easy, but I was wondering if there is anything that would allow me to understand what section of the file is currently being read so that I can pull out some stats about the playback from the server side. – Sync Dec 09 '17 at 11:22
0

I just ran your code and worked in the latest version of Chrome. My video was a MP4 file with H264 video and AAC audio (Both codecs are pretty commonplace and widely supported).

You should convert your video to a supported format for browsers. See this MDN docs to see supported formats and pay attention to "Browser compatibility" part of it.

Arman Ordookhani
  • 6,031
  • 28
  • 41