· 7 years ago · Jun 10, 2018, 04:58 AM
1package main
2
3import (
4 "crypto/hmac"
5 "crypto/sha1"
6 "encoding/base64"
7 "encoding/hex"
8 "io"
9 "strconv"
10 "time"
11
12 "github.com/gin-gonic/gin"
13)
14
15var (
16 secret_key string = base64.StdEncoding.EncodeToString([]byte("YOUR KEY HERE"))
17 authorize_table map[string]string = map[string]string{
18 "test": "123.mp4",
19 }
20)
21
22func main() {
23
24 r := gin.Default()
25
26 //Serve Media File, /serveMedia/this_is_hash
27 r.GET("/serveMedia/:hash", func(c *gin.Context) {
28 filepath := authorize_table[c.Param("hash")]
29 c.File(filepath)
30 })
31
32 //Show the 10 min exp link with token
33 r.GET("/generateMediaUrl", func(c *gin.Context) {
34 //simulate hash
35 hash := "kfskfoksdokfpsd"
36
37 //add hash with filename to table
38 authorize_table[hash] = "./1.mp4"
39
40 //build token
41 ru := "/serveMedia/" + hash
42 urltoken := generateToken(ru, makeExpTime())
43 c.String(200, ru+"?token="+urltoken)
44 })
45
46 r.GET("/removeFile", func(c *gin.Context) {
47 //simulate hash
48 hash := "kfskfoksdokfpsd"
49
50 //delete file in table
51 delete(authorize_table, hash)
52 c.JSON(200, "good")
53 })
54
55 r.Run(":80")
56
57}
58
59func makeExpTime() int64 {
60 t := time.Now().Local().Add(
61 time.Hour*time.Duration(0) +
62 time.Minute*time.Duration(10) + //after 10 minute
63 time.Second*time.Duration(0))
64
65 return t.Unix()
66}
67
68func generateToken(urlpath string, expTime int64) string {
69 base64data, _ := base64.StdEncoding.DecodeString(secret_key)
70 timestamp := strconv.FormatInt(expTime, 10)
71 unsigndata := urlpath + timestamp
72
73 //sha1
74 h := hmac.New(sha1.New, base64data)
75 io.WriteString(h, unsigndata)
76 signdata := h.Sum(nil)
77 strTypeSignData := hex.EncodeToString(signdata)
78
79 //token format
80 token := timestamp + "_" + strTypeSignData
81 return token
82}