package main import ( "crypto/md5" "fmt" "math/rand" "regexp" "time" ) func splitUrl(url string) []string { reg := regexp.MustCompile("^(http://|https://)?([^/?]+)(/[^?]*)?(\\?.*)?$") return reg.FindStringSubmatch(url) } func getRandom() int { return rand.New(rand.NewSource(time.Now().UnixNano())).Int() } func GenUrl(url, secretKey string, ts int64) string { params := splitUrl(url) scheme, host, path, args := params[1], params[2], params[3], params[4] randValue := getRandom() signature := md5.Sum([]byte(fmt.Sprintf("%s-%d-%d-%s", path, ts, randValue, secretKey))) authValue := fmt.Sprintf("%d-%d-%x", ts, randValue, signature) authArg := fmt.Sprintf("auth_key=%s", authValue) if args == "" { return fmt.Sprintf("%s%s%s?%s", scheme, host, path, authArg) } else { return fmt.Sprintf("%s%s%s%s&%s", scheme, host, path, args, authArg) } } func main() { url := "http://www.test.com/a.txt?a=b&c=d" secretKey := "secretKey" ts := time.Now().Unix() fmt.Printf("OriginUrl: %s\n", url) fmt.Printf("AuthUrl:%s\n", GenUrl(url, secretKey, ts)) }