url.go 1.9 KB

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