EasyDSS视频平台观看视频推流直播不需要安装插件,网页直接即可播放,通过浏览器进入平台即可进行配置,对用户来说,便捷可控,无需另行搭建服务器,具有很大的优势。

 

在原先的EasyDSS设计中,EasyDSS平台直接获取到流媒体的存储hls的路径,然后将该路径变为可访问资源路径即可。但是该种设计方式,在流媒体在其他机器上的时候就会出现无法访问hls流的情况,因此更改hls的访问路径。

func HlsHandler() gin.HandlerFunc {
   return func(c *gin.Context) {
      defer func() {
         if err := recover(); err != nil {
            gErrorLogger.Error(fmt.Sprintf("panic %s\n", err))
            gErrorLogger.Error(fmt.Sprint(string(debug.Stack())))
         }
      }()

      // /hls/stream_1/playlist.m3u8
      path := c.Request.URL.Path

      if strings.HasSuffix(path, ".m3u8") || strings.HasSuffix(path, ".ts") {
         target := fmt.Sprintf("127.0.0.1:%v", mediaserver.GetHttpPort())
         director := func(req *http.Request) {
            req.URL.Scheme = "http"
            req.URL.Host = target
            req.URL.RawQuery = ""

            if strings.HasSuffix(path, ".m3u8") {
               // 如果是老的 EasyDSS 路径,则修改为新的 m3u8 路径
               // 老的路径为 /hls/stream_1/stream_1_live.m3u8
               if strings.HasSuffix(path, "_live.m3u8") {
                  index := strings.LastIndex(path, "/")
                  basePath := path[:index+1]
                  req.URL.Path = basePath + mediaserver.HlsPlayList
               }
            }

         }
         tranport := &ShutDownTransport{
            Trans: &http.Transport{
               Proxy: http.ProxyFromEnvironment,
               DialContext: (&net.Dialer{
                  Timeout:   30 * time.Second,
                  KeepAlive: 30 * time.Second,
               }).DialContext,
               ForceAttemptHTTP2:     true,
               MaxIdleConns:          100,
               IdleConnTimeout:       90 * time.Second,
               TLSHandshakeTimeout:   10 * time.Second,
               ExpectContinueTimeout: 1 * time.Second,
               ResponseHeaderTimeout: 10 * time.Second,
            },
         }

         errHandle := func(res http.ResponseWriter, req *http.Request, err error) {
            log.Println("hls proxy is error : ", err)
            c.AbortWithError(http.StatusVariantAlsoNegotiates, err)
         }
         proxy := &httputil.ReverseProxy{
            Director:     director,
            Transport:    tranport,
            ErrorHandler: errHandle,
         }

         proxy.ServeHTTP(c.Writer, c.Request)

         c.Next()
         return
      } else {
         c.AbortWithStatusJSON(http.StatusBadRequest, "BadRequest")
      }

      return
   }
}

以上代码主要使用httputil.ReverseProxy实现反向代理。proxy.ServeHTTP()函数即可实现http的反向代理功能。

posted on 2021-10-28 17:52  EasyDSS  阅读(44)  评论(0编辑  收藏  举报