Last active
June 7, 2018 06:22
-
-
Save hpcslag/3904e246bd183ae91780df86d941a12e to your computer and use it in GitHub Desktop.
Golang Implement for Generate "FastlyCDN" URL Token Validation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/hmac" | |
"crypto/sha1" | |
"encoding/base64" | |
"encoding/hex" | |
"io" | |
"strconv" | |
"time" | |
"github.com/gin-gonic/gin" | |
) | |
var ( | |
secret_key string = base64.StdEncoding.EncodeToString([]byte("YOUR KEY HERE")) | |
authorize_table map[string]string = map[string]string{ | |
"test": "123.mp4", | |
} | |
) | |
func main() { | |
r := gin.Default() | |
//Serve Media File, /serveMedia/this_is_hash | |
r.GET("/serveMedia/:hash", func(c *gin.Context) { | |
filepath := authorize_table[c.Param("hash")] | |
c.File(filepath) | |
}) | |
//Show the 10 min exp link with token | |
r.GET("/generateMediaUrl", func(c *gin.Context) { | |
//simulate hash | |
hash := "kfskfoksdokfpsd" | |
//add hash with filename to table | |
authorize_table[hash] = "./1.mp4" | |
//build token | |
ru := "/serveMedia/" + hash | |
urltoken := generateToken(ru, makeExpTime()) | |
c.String(200, ru+"?token="+urltoken) | |
}) | |
r.GET("/removeFile", func(c *gin.Context) { | |
//simulate hash | |
hash := "kfskfoksdokfpsd" | |
//delete file in table | |
delete(authorize_table, hash) | |
c.JSON(200, "good") | |
}) | |
r.Run(":80") | |
} | |
func makeExpTime() int64 { | |
t := time.Now().Local().Add( | |
time.Hour*time.Duration(0) + | |
time.Minute*time.Duration(10) + //after 10 minute | |
time.Second*time.Duration(0)) | |
return t.Unix() | |
} | |
func generateToken(urlpath string, expTime int64) string { | |
base64data, _ := base64.StdEncoding.DecodeString(secret_key) | |
timestamp := strconv.FormatInt(expTime, 10) | |
unsigndata := urlpath + timestamp | |
//sha1 | |
h := hmac.New(sha1.New, base64data) | |
io.WriteString(h, unsigndata) | |
signdata := h.Sum(nil) | |
strTypeSignData := hex.EncodeToString(signdata) | |
//token format | |
token := timestamp + "_" + strTypeSignData | |
return token | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment