url.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package sprig
  2. import (
  3. "fmt"
  4. "net/url"
  5. "reflect"
  6. )
  7. func dictGetOrEmpty(dict map[string]interface{}, key string) string {
  8. value, ok := dict[key]
  9. if !ok {
  10. return ""
  11. }
  12. tp := reflect.TypeOf(value).Kind()
  13. if tp != reflect.String {
  14. panic(fmt.Sprintf("unable to parse %s key, must be of type string, but %s found", key, tp.String()))
  15. }
  16. return reflect.ValueOf(value).String()
  17. }
  18. func urlParse(v string) map[string]interface{} {
  19. dict := map[string]interface{}{}
  20. parsedURL, err := url.Parse(v)
  21. if err != nil {
  22. panic(fmt.Sprintf("unable to parse url: %s", err))
  23. }
  24. dict["scheme"] = parsedURL.Scheme
  25. dict["host"] = parsedURL.Host
  26. dict["hostname"] = parsedURL.Hostname()
  27. dict["path"] = parsedURL.Path
  28. dict["query"] = parsedURL.RawQuery
  29. dict["opaque"] = parsedURL.Opaque
  30. dict["fragment"] = parsedURL.Fragment
  31. if parsedURL.User != nil {
  32. dict["userinfo"] = parsedURL.User.String()
  33. } else {
  34. dict["userinfo"] = ""
  35. }
  36. return dict
  37. }
  38. func urlJoin(d map[string]interface{}) string {
  39. resURL := url.URL{
  40. Scheme: dictGetOrEmpty(d, "scheme"),
  41. Host: dictGetOrEmpty(d, "host"),
  42. Path: dictGetOrEmpty(d, "path"),
  43. RawQuery: dictGetOrEmpty(d, "query"),
  44. Opaque: dictGetOrEmpty(d, "opaque"),
  45. Fragment: dictGetOrEmpty(d, "fragment"),
  46. }
  47. userinfo := dictGetOrEmpty(d, "userinfo")
  48. var user *url.Userinfo
  49. if userinfo != "" {
  50. tempURL, err := url.Parse(fmt.Sprintf("proto://%s@host", userinfo))
  51. if err != nil {
  52. panic(fmt.Sprintf("unable to parse userinfo in dict: %s", err))
  53. }
  54. user = tempURL.User
  55. }
  56. resURL.User = user
  57. return resURL.String()
  58. }