live_sign.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package main
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "fmt"
  6. "git.wanpinghui.com/WPH/go_common/wph"
  7. "git.wanpinghui.com/WPH/go_common/wph/date"
  8. "net/url"
  9. "strings"
  10. )
  11. func GetLiveSingedURL(scheme, host, app, stream, key string, expire date.Datetime, args url.Values) string {
  12. scheme = strings.TrimSpace(scheme)
  13. host = strings.TrimSpace(host)
  14. app = strings.TrimSpace(app)
  15. stream = strings.TrimSpace(stream)
  16. key = strings.TrimSpace(key)
  17. if scheme == "" {
  18. scheme = "rtmp"
  19. }
  20. if host == "" || app == "" || stream == "" || key == "" || expire.IsZero() {
  21. return ""
  22. }
  23. nonce := wph.NextId() // 随机码
  24. path := fmt.Sprintf("/%s/%s", app, stream) // /AppName/StreamName及后缀
  25. paramStr := fmt.Sprintf("%d-%d-0", expire.Unix(), nonce) // 地址过期时间UNIX时间戳-随机码-0
  26. origin := fmt.Sprintf("%s-%s-%s", path, paramStr, key) // 待签名字符串
  27. md5hash := md5sum(origin)
  28. result := fmt.Sprintf("%s://%s%s?auth_key=%s-%s", scheme, host, path, paramStr, md5hash) // 结果URL
  29. if nil != args && len(args) > 0 {
  30. result = fmt.Sprintf("%s&%s", result, args.Encode())
  31. }
  32. return result
  33. }
  34. func md5sum(str string) string {
  35. h := md5.New()
  36. h.Write([]byte(str))
  37. return hex.EncodeToString(h.Sum(nil))
  38. }
  39. var DefaultAudioArgs url.Values
  40. func init() {
  41. DefaultAudioArgs = url.Values{}
  42. DefaultAudioArgs.Add("onlyaudio", "1")
  43. }
  44. // 测试
  45. func main() {
  46. expire := date.Now().AddDays(1)
  47. scheme := `rtmp`
  48. appName := `shy-live-test`
  49. // 以下参数正常应由配置读取
  50. pushHostName := `livepush-appmedia.zlzgy.org.cn`
  51. pullHostName := `live-appmedia.zlzgy.org.cn`
  52. pushKey := `N3IC5OfIBg`
  53. pullKey := `utPuNSNngo`
  54. // 视频直播
  55. videoStreamName := wph.NextId().String()
  56. videoPushUrl := GetLiveSingedURL(scheme, pushHostName, appName,
  57. videoStreamName, pushKey, expire, nil)
  58. println(`video push url:`, videoPushUrl)
  59. videoPullUrl := GetLiveSingedURL(scheme, pullHostName, appName,
  60. videoStreamName, pullKey, expire, nil)
  61. println(`video pull url:`, videoPullUrl)
  62. // 音频直播
  63. audioStreamName := wph.NextId().String()
  64. audioPushUrl := GetLiveSingedURL(scheme, pushHostName, appName,
  65. audioStreamName, pushKey, expire, DefaultAudioArgs)
  66. println(`audio push url:`, audioPushUrl)
  67. audioPullUrl := GetLiveSingedURL(scheme, pullHostName, appName,
  68. audioStreamName, pullKey, expire, DefaultAudioArgs)
  69. println(`audio pull url:`, audioPullUrl)
  70. }