目录

问题

解决


问题

如何根据一个流媒体地址URL判断对应的流媒体协议,比如RTMP、RTSP协议等。

解决

这里提供一个方法,可以直接拿来用。

func getProtocol(url string) (string, error) {
        // golang的判断语句没有括号,一开始挺不适应的
	if url != "" {
                // 获取冒号索引位置
		index := strings.Index(url, ":")
                // 找到了说明URL正确,否则报错
		if index > 0 { 
                        // 这里需要注意两点:
                        // 1. golang字符串的索引原则是左闭右开
                        // 2. 协议类型最好进行格式化处理再输出返回,比如这里是“最大化”(大写格式)
			return strings.ToUpper(url[0:index]), nil
		} else { 
                        // 注意提前定义ErrorInvalidURL类型
			return "", ErrorInvalidURL
		}
	}
	return "", ErrorNullURL
}

getProtocol() 方法会输出流媒体协议的大写字符串标识,最后给出完整的代码:

package main

import(
	"fmt"
	"strings"
)

var (
	ErrorNullURL    = fmt.Errorf("url is null")
	ErrorInvalidURL = fmt.Errorf("url is not valid")
)

func getProtocol(url string) (string, error) {
	if url != "" {
		index := strings.Index(url, ":")
		if index > 0 {
			return strings.ToUpper(url[0:index]), nil
		} else {
			return "", ErrorInvalidURL
		}
	}
	return "", ErrorNullURL
}

func main() {
	url1 := "rtmp://172.0.0.1:1935/test/live"
	url2 := "rtsp://172.0.0.1:1554/live"
	if pro, err := getProtocol(url1); err == nil {
		fmt.Println("url1 protocol: ", pro)
	}
	if pro, err := getProtocol(url2); err == nil {
		fmt.Println("url2 protocol: ", pro)
	}
}

运行结果如下:

url1 protocol:  RTMP
url2 protocol:  RTSP

截图:

Go根据流地址判断流媒体协议类型_go