base_model.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package model
  2. import (
  3. "crypto/hmac"
  4. "crypto/sha1"
  5. "encoding/base64"
  6. "fmt"
  7. "hash"
  8. "math/rand"
  9. "net/url"
  10. "path/filepath"
  11. "strings"
  12. "time"
  13. )
  14. // const .
  15. const (
  16. _template = "%s\n%s\n%s\n%d\n"
  17. BfsEasyPath = "/bfs/mcn"
  18. TimeFormatSec = "2006-01-02 15:04:05"
  19. TimeFormatDay = "2006-01-02"
  20. )
  21. // BuildBfsURL is.
  22. func BuildBfsURL(raw string, appkey, secret, bucket, ePath string) string {
  23. if raw == "" {
  24. return ""
  25. }
  26. ori, err := url.Parse(raw)
  27. if err != nil {
  28. return raw
  29. }
  30. if strings.HasPrefix(ori.Path, ePath) {
  31. token := authorize(appkey, secret, "GET", bucket, filepath.Base(ori.Path), time.Now().Unix())
  32. p := url.Values{}
  33. p.Set("token", token)
  34. ori.RawQuery = p.Encode()
  35. }
  36. if ori.Hostname() == "" {
  37. ori.Host = fmt.Sprintf("i%d.hdslb.com", rand.Int63n(3))
  38. ori.Scheme = "http"
  39. }
  40. return ori.String()
  41. }
  42. // Authorize returns authorization for upload file to bfs
  43. func authorize(key, secret, method, bucket, file string, expire int64) (authorization string) {
  44. var (
  45. content string
  46. mac hash.Hash
  47. signature string
  48. )
  49. content = fmt.Sprintf(_template, method, bucket, file, expire)
  50. mac = hmac.New(sha1.New, []byte(secret))
  51. mac.Write([]byte(content))
  52. signature = base64.StdEncoding.EncodeToString(mac.Sum(nil))
  53. authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
  54. return
  55. }