| 1 | // Implementation of URIRef required for nodes in the rdf graph. |
| 2 | |
| 3 | package uri |
| 4 | |
| 5 | import ( |
| 6 | "fmt" |
| 7 | "net/url" |
| 8 | "strings" |
| 9 | ) |
| 10 | |
| 11 | type URIRef struct { |
| 12 | /** |
| 13 | * A URI Reference is formed of one or two components: |
| 14 | * Base: base URL / URI. Can optionally end in # char |
| 15 | * Fragment: relative component of url [optional] |
| 16 | * A valid uri is: |
| 17 | * base#fragment or base# |
| 18 | * For example: |
| 19 | * https://www.w3.org/TR/skos-reference/#L1302 is a valid URIRef with |
| 20 | * Base = https://www.w3.org/TR/skos-reference/ |
| 21 | * Fragment = L1302 |
| 22 | */ |
| 23 | uri string |
| 24 | } |
| 25 | |
| 26 | // constructor for URIRef |
| 27 | func NewURIRef(uri string) (uriref URIRef, err error) { |
| 28 | /** |
| 29 | * Usage and equivalence: |
| 30 | * base := "https://www.w3.org/TR/skos-reference/" |
| 31 | * fragment: "L1302" |
| 32 | * uriref := NewURIRef(base, fragment) |
| 33 | * uriref -> "https://www.w3.org/TR/skos-reference/#L1302" |
| 34 | */ |
| 35 | |
| 36 | // validating the input uri |
| 37 | _, err = url.ParseRequestURI(uri) |
| 38 | if err != nil { |
| 39 | return uriref, fmt.Errorf("Malformed URI: %v", err) |
| 40 | } |
| 41 | |
| 42 | // adding a # to the end if it doesn't end in # already. |
| 43 | if !strings.HasSuffix(uri, "#") { |
| 44 | uri += "#" |
| 45 | } |
| 46 | |
| 47 | // validate uri after addition of # at the end |
| 48 | return URIRef{uri}, err |
| 49 | } |
| 50 | |
| 51 | // join the fragment to the uri of current object |
| 52 | func (uriref *URIRef) AddFragment(frag string) (retURI URIRef) { |
| 53 | if strings.HasPrefix(frag, "#") { |
| 54 | frag = frag[1:] |
| 55 | } |
| 56 | |
| 57 | // validating the relative uri |
| 58 | _, err := url.ParseRequestURI(uriref.uri + frag) |
| 59 | if err != nil { |
| 60 | return |
| 61 | } |
| 62 | |
| 63 | // relative uri is fine, return a new object of uriref. |
| 64 | return URIRef{uriref.uri + frag} |
| 65 | } |
| 66 | |
| 67 | // returns string representation of the uriref |
| 68 | func (uriref *URIRef) String() string { |
| 69 | return uriref.uri |
| 70 | } |