Skip to content

Instantly share code, notes, and snippets.

@tenthree
Created September 11, 2018 08:57
Show Gist options
  • Select an option

  • Save tenthree/b516dfaaad3e8ae0c3ac91e782df5793 to your computer and use it in GitHub Desktop.

Select an option

Save tenthree/b516dfaaad3e8ae0c3ac91e782df5793 to your computer and use it in GitHub Desktop.
radio stream generator in go
package hi
import (
"crypto/md5"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
)
// Httpbin represents network connection information
type Httpbin struct {
IP string `json:"origin"`
}
// GenIP will retrive current ip address by httpbin service
func GenIP() string {
res, err := http.Get("https://httpbin.org/ip")
if err != nil {
fmt.Println(err.Error())
return ""
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err.Error())
return ""
}
model := Httpbin{}
json.Unmarshal(body, &model)
return model.IP
}
// GenToken will generate token with path, timestamp, ip and suffix key
func GenToken(path string, timestamp int64, ip string, suffixKey string) string {
secret := "radio@himediaservice#t"
var builder strings.Builder
fmt.Fprint(&builder, path)
fmt.Fprint(&builder, strconv.FormatInt(timestamp, 10))
fmt.Fprint(&builder, ip)
fmt.Fprint(&builder, secret)
fmt.Fprint(&builder, suffixKey)
source := builder.String()
hash := md5.New()
hash.Write([]byte(source))
hashInBase64 := base64.StdEncoding.EncodeToString(hash.Sum(nil))
step1 := strings.Replace(hashInBase64, "+", "-", -1)
step2 := strings.Replace(step1, "/", "_", -1)
return strings.Replace(step2, "=", "", -1)
}
// GenStreamURL will generate radio stream resource url
func GenStreamURL(channel string) string {
entry := "https://radio-hichannel.cdn.hinet.net"
now := time.Now()
timestamp := now.Unix()
path := fmt.Sprintf("/live/pool/hich-%s/ra-hls/", channel)
ip := GenIP()
expire1 := timestamp + (5 * 60)
expire2 := expire1 + (8 * 60 * 60)
token1 := GenToken(path, expire1, ip, "1")
token2 := GenToken(path, expire2, ip, "2")
params := fmt.Sprintf("token1=%s&token2=%s&expire1=%d&expire2=%d", token1, token2, expire1, expire2)
return fmt.Sprintf("%s%sindex.m3u8?%s", entry, path, params)
// return fmt.Sprintf("%s%shich-%s-audio_track=128000.m3u8?%s", entry, path, channel, params)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment