base_model.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. AllActiveTid = 65535 //mcn_data_summary表active_tid所有分区
  21. DefaultTyName = "默认"
  22. )
  23. // BuildBfsURL is.
  24. func BuildBfsURL(raw string, appkey, secret, bucket, ePath string) string {
  25. if raw == "" {
  26. return ""
  27. }
  28. ori, err := url.Parse(raw)
  29. if err != nil {
  30. return raw
  31. }
  32. if strings.HasPrefix(ori.Path, ePath) {
  33. token := authorize(appkey, secret, "GET", bucket, filepath.Base(ori.Path), time.Now().Unix())
  34. p := url.Values{}
  35. p.Set("token", token)
  36. ori.RawQuery = p.Encode()
  37. }
  38. if ori.Hostname() == "" {
  39. ori.Host = fmt.Sprintf("i%d.hdslb.com", rand.Int63n(3))
  40. ori.Scheme = "http"
  41. }
  42. return ori.String()
  43. }
  44. // Authorize returns authorization for upload file to bfs
  45. func authorize(key, secret, method, bucket, file string, expire int64) (authorization string) {
  46. var (
  47. content string
  48. mac hash.Hash
  49. signature string
  50. )
  51. content = fmt.Sprintf(_template, method, bucket, file, expire)
  52. mac = hmac.New(sha1.New, []byte(secret))
  53. mac.Write([]byte(content))
  54. signature = base64.StdEncoding.EncodeToString(mac.Sum(nil))
  55. authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
  56. return
  57. }