使用 go gin 提供视频

serve video with go gin

我正在编写一个 api 服务器,用于通过 go-gin 框架上传和提供视频和图像。我已经将我的视频上传到另一个主机,并且成功了

router := gin.Default()

    //config := cors.DefaultConfig()
    //config.AllowAllOrigins = true

    routerConfig := cors.Config{
        AllowAllOrigins:  true,
        AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},
        AllowHeaders:     []string{"X-Requested-With", "Authorization", "Origin", "Content-Length", "Content-Type"},
        AllowCredentials: false,
        MaxAge:           12 * time.Hour,
    }

    router.Use(cors.New(routerConfig))

    router.StaticFS("/public", http.Dir("static"))

    err := router.Run(":5000")
    if err != nil {
        panic(err)
    }

当我尝试通过 chromium 访问 http://localhost:5000/public/{image_url}.png 时。它加载到浏览器。但是当我通过 chromium 访问 http://localhost:5000/public/{video_url}.mp4 时,它无法从浏览器加载任何内容(它无法接收)

谁能帮我解释一下我做错了什么?

更新:

也许我错过了这个内容:

这是我调用 GET 请求时的 2 个 http 包

您的问题有 2 种可能的解释。

  1. 这不是问题,因为您的浏览器不支持 运行 视频。
  2. (这是更可能的解释)您没有为流式视频设置正确的 header,因此浏览器无法识别或不知道如何处理 URL。

例如我从这个 video 得到的,当你检查响应 Header 时,它应该显示

content-length: 1570024
content-range: bytes 0-1570023/1570024
content-type: video/mp4

我的建议是使用http.ServeFile which supports serving Range requests. See related questions, GoLang http webserver provide video (mp4) and How to serve http partial content with Go?.

已更新

检查Gin StaticFS Godoc后,我认为它不支持范围header。

测试后

所以我试过你的代码但我错了,Gin StaticFS 可以提供像视频这样的内容范围

这是我的屏幕截图,已经使用 Chromium 对其进行了测试并且运行良好:

我的结论是:您的 OS 不支持您的 Chromium 或您的编解码器或视频编解码器有问题(我不知道您的 OS 是什么),检查这个MP4 not playing on Chrome version 27.0:

due to Chrome removing support for h264, on some machines, mp4 videos encoded with it will either not work (throwing an Parser error when viewing under Firebug/Network tab - consistent with issue submitted here), or crash the browser, depending upon the encoding settings

it isn't consistent - it entirely depends upon the codecs installed on the computer - while I didn't encounter this issue on my machine, we did have one in the office where the issue occurred (and thus we used this one for testing)

it might to do with Quicktime / divX settings (the machine in question had an older version of Quicktime than my native one - we didn't want to loose our testing pc though, so we didn't update it).