url.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package url
  2. import (
  3. "git.nspix.com/golang/micro/helper/tokenize"
  4. "net/url"
  5. "os"
  6. "time"
  7. )
  8. const (
  9. AuthFormField = "access_token"
  10. AuthMethodField = "auth_method"
  11. AuthMethodGateway = "Sugo"
  12. )
  13. type (
  14. Options struct {
  15. Schema string
  16. Host string
  17. Path string // encoded query values, without '?'
  18. Fragment string // fragment for references, without '#'
  19. Params map[string]string
  20. EnableAuth bool //enable auth
  21. AuthAppName string //auth app name
  22. AuthUserID string
  23. AuthExpired time.Duration
  24. }
  25. Option func(o *Options)
  26. )
  27. func newOptions() *Options {
  28. return &Options{
  29. Schema: "https",
  30. Host: os.Getenv("DOMAIN_NAME"),
  31. Params: make(map[string]string),
  32. }
  33. }
  34. func WithSchema(schema string) Option {
  35. return func(o *Options) {
  36. o.Schema = schema
  37. }
  38. }
  39. func WithAuth(app string, uid string, expired time.Duration) Option {
  40. return func(o *Options) {
  41. o.EnableAuth = true
  42. o.AuthAppName = app
  43. o.AuthUserID = uid
  44. o.AuthExpired = expired
  45. }
  46. }
  47. func WithFragment(fragment string) Option {
  48. return func(o *Options) {
  49. o.Fragment = fragment
  50. }
  51. }
  52. func WithHost(host string) Option {
  53. return func(o *Options) {
  54. o.Host = host
  55. }
  56. }
  57. func WithPath(path string) Option {
  58. return func(o *Options) {
  59. o.Path = path
  60. }
  61. }
  62. func WithParams(ps map[string]string) Option {
  63. return func(o *Options) {
  64. o.Params = ps
  65. }
  66. }
  67. func Create(opts ...Option) string {
  68. o := newOptions()
  69. for _, cb := range opts {
  70. cb(o)
  71. }
  72. qs := url.Values{}
  73. for k, v := range o.Params {
  74. qs.Set(k, v)
  75. }
  76. if o.EnableAuth {
  77. if token, err := tokenize.Encode(o.AuthAppName, o.AuthUserID, time.Now().Add(o.AuthExpired)); err == nil {
  78. qs.Set(AuthFormField, token)
  79. qs.Set(AuthMethodField, AuthMethodGateway)
  80. }
  81. }
  82. uri := url.URL{
  83. Scheme: o.Schema,
  84. Host: o.Host,
  85. Path: o.Path,
  86. RawQuery: qs.Encode(),
  87. }
  88. return uri.String()
  89. }