uri.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package uri
  2. import (
  3. "net/url"
  4. "strings"
  5. "github.com/pkg/errors"
  6. )
  7. // URI implements a parser for a URI format based on the the PKCS #11 URI Scheme
  8. // defined in https://tools.ietf.org/html/rfc7512
  9. //
  10. // These URIs will be used to define the key names in a KMS.
  11. type URI struct {
  12. *url.URL
  13. Values url.Values
  14. }
  15. // New creates a new URI from a scheme and key-value pairs.
  16. func New(scheme string, values url.Values) *URI {
  17. return &URI{
  18. URL: &url.URL{
  19. Scheme: scheme,
  20. Opaque: strings.ReplaceAll(values.Encode(), "&", ";"),
  21. },
  22. Values: values,
  23. }
  24. }
  25. // NewFile creates an uri for a file.
  26. func NewFile(path string) *URI {
  27. return &URI{
  28. URL: &url.URL{
  29. Scheme: "file",
  30. Path: path,
  31. },
  32. }
  33. }
  34. // HasScheme returns true if the given uri has the given scheme, false otherwise.
  35. func HasScheme(scheme, rawuri string) bool {
  36. u, err := url.Parse(rawuri)
  37. if err != nil {
  38. return false
  39. }
  40. return strings.EqualFold(u.Scheme, scheme)
  41. }
  42. // Parse returns the URI for the given string or an error.
  43. func Parse(rawuri string) (*URI, error) {
  44. u, err := url.Parse(rawuri)
  45. if err != nil {
  46. return nil, errors.Wrapf(err, "error parsing %s", rawuri)
  47. }
  48. if u.Scheme == "" {
  49. return nil, errors.Errorf("error parsing %s: scheme is missing", rawuri)
  50. }
  51. v, err := url.ParseQuery(u.Opaque)
  52. if err != nil {
  53. return nil, errors.Wrapf(err, "error parsing %s", rawuri)
  54. }
  55. return &URI{
  56. URL: u,
  57. Values: v,
  58. }, nil
  59. }
  60. // ParseWithScheme returns the URI for the given string only if it has the given
  61. // scheme.
  62. func ParseWithScheme(scheme, rawuri string) (*URI, error) {
  63. u, err := Parse(rawuri)
  64. if err != nil {
  65. return nil, err
  66. }
  67. if !strings.EqualFold(u.Scheme, scheme) {
  68. return nil, errors.Errorf("error parsing %s: scheme not expected", rawuri)
  69. }
  70. return u, nil
  71. }
  72. // Get returns the first value in the uri with the give n key, it will return
  73. // empty string if that field is not present.
  74. func (u *URI) Get(key string) string {
  75. return u.Values.Get(key)
  76. }