url.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package url
  2. import (
  3. "net/url"
  4. "os"
  5. )
  6. type (
  7. Options struct {
  8. Schema string
  9. Host string
  10. Path string // encoded query values, without '?'
  11. Fragment string // fragment for references, without '#'
  12. Params map[string]string
  13. }
  14. Option func(o *Options)
  15. )
  16. func newOptions() *Options {
  17. return &Options{
  18. Schema: "https",
  19. Host: os.Getenv("DOMAIN_NAME"),
  20. Params: make(map[string]string),
  21. }
  22. }
  23. func WithSchema(schema string) Option {
  24. return func(o *Options) {
  25. o.Schema = schema
  26. }
  27. }
  28. func WithFragment(fragment string) Option {
  29. return func(o *Options) {
  30. o.Fragment = fragment
  31. }
  32. }
  33. func WithHost(host string) Option {
  34. return func(o *Options) {
  35. o.Host = host
  36. }
  37. }
  38. func WithPath(path string) Option {
  39. return func(o *Options) {
  40. o.Path = path
  41. }
  42. }
  43. func WithParams(ps map[string]string) Option {
  44. return func(o *Options) {
  45. o.Params = ps
  46. }
  47. }
  48. func Create(opts ...Option) string {
  49. o := newOptions()
  50. for _, cb := range opts {
  51. cb(o)
  52. }
  53. qs := url.Values{}
  54. for k, v := range o.Params {
  55. qs.Set(k, v)
  56. }
  57. uri := url.URL{
  58. Scheme: o.Schema,
  59. Host: o.Host,
  60. Path: o.Path,
  61. RawQuery: qs.Encode(),
  62. }
  63. return uri.String()
  64. }