目录
问题
解决
问题
如何根据一个流媒体地址URL判断对应的流媒体协议,比如RTMP、RTSP协议等。
解决
这里提供一个方法,可以直接拿来用。
1 func getProtocol(url string) (string, error) { 2 if url != "" { 3 index := strings.Index(url, ":") 4 if index > 0 { 5 return strings.ToUpper(url[0:index]), nil 6 } else { 7 return "", ErrorInvalidURL 8 } 9 } 10 return "", ErrorNullURL 11}
getProtocol() 方法会输出流媒体协议的大写字符串标识,最后给出完整的代码:
1 package main 2 3import( 4 "fmt" 5 "strings" 6) 7 8var ( 9 ErrorNullURL = fmt.Errorf("url is null") 10 ErrorInvalidURL = fmt.Errorf("url is not valid") 11) 12 13func getProtocol(url string) (string, error) { 14 if url != "" { 15 index := strings.Index(url, ":") 16 if index > 0 { 17 return strings.ToUpper(url[0:index]), nil 18 } else { 19 return "", ErrorInvalidURL 20 } 21 } 22 return "", ErrorNullURL 23} 24 25func main() { 26 url1 := "rtmp://172.0.0.1:1935/test/live" 27 url2 := "rtsp://172.0.0.1:1554/live" 28 if pro, err := getProtocol(url1); err == nil { 29 fmt.Println("url1 protocol: ", pro) 30 } 31 if pro, err := getProtocol(url2); err == nil { 32 fmt.Println("url2 protocol: ", pro) 33 } 34}
运行结果如下:
url1 protocol: RTMP url2 protocol: RTSP
截图:

