From 5f9c8a16b38b0ac7546cfde9c4ef72051c329d10 Mon Sep 17 00:00:00 2001 From: ccamel Date: Thu, 13 Apr 2023 08:56:11 +0200 Subject: [PATCH] feat(logic): add some functions to deal with urls --- x/logic/util/url.go | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 x/logic/util/url.go diff --git a/x/logic/util/url.go b/x/logic/util/url.go new file mode 100644 index 00000000..56100e2c --- /dev/null +++ b/x/logic/util/url.go @@ -0,0 +1,37 @@ +package util + +import ( + "net/url" +) + +// UrlMatches is a function that returns a function that matches the given url against the given other item. +// +// The function matches the components of the given url against the components of the given other url. If the component +// of the given other url is empty, it is considered to match the component of the given url. +// For example: +// - matchUrl("http://example.com/foo")("http://example.com/foo") -> true +// - matchUrl("http://example.com/foo")("http://example.com/foo?bar=baz") -> false +// - matchUrl("tel:123456789")("tel:") -> true +// +// The function is curried, and is a binary relation that is reflexive, associative (but not commutative). +func UrlMatches(this *url.URL) func(*url.URL) bool { + return func(that *url.URL) bool { + return (that.Scheme == "" || that.Scheme == this.Scheme) && + (that.Opaque == "" || that.Opaque == this.Opaque) && + (that.User == nil || that.User.String() == "" || that.User.String() == this.User.String()) && + (that.Host == "" || that.Host == this.Host) && + (that.Path == "" || that.Path == this.Path) && + (that.RawQuery == "" || that.RawQuery == this.RawQuery) && + (that.Fragment == "" || that.Fragment == this.Fragment) + } +} + +// ParseUrlMust parses the given url and panics if it fails. +// You have been warned. +func ParseUrlMust(s string) *url.URL { + u, err := url.Parse(s) + if err != nil { + panic(err) + } + return u +}