2024-03-20 19:23:31 +00:00
|
|
|
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
|
2024-03-22 17:39:06 +00:00
|
|
|
|
2024-03-20 16:15:27 +00:00
|
|
|
package resource
|
|
|
|
|
|
|
|
import (
|
2024-03-25 20:31:06 +00:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"net/url"
|
2024-04-03 16:54:50 +00:00
|
|
|
"strings"
|
2024-03-20 16:15:27 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2024-03-25 20:31:06 +00:00
|
|
|
ErrUnknownResourceType = errors.New("Unknown resource type")
|
|
|
|
ResourceTypes *Types = NewTypes()
|
2024-03-20 16:15:27 +00:00
|
|
|
)
|
|
|
|
|
2024-04-03 16:54:50 +00:00
|
|
|
type TypeName string //`json:"type"`
|
|
|
|
|
2024-03-20 19:23:31 +00:00
|
|
|
type TypeFactory func(*url.URL) Resource
|
2024-03-20 16:15:27 +00:00
|
|
|
|
|
|
|
type Types struct {
|
2024-03-25 20:31:06 +00:00
|
|
|
registry map[string]TypeFactory
|
2024-03-20 16:15:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewTypes() *Types {
|
2024-03-25 20:31:06 +00:00
|
|
|
return &Types{registry: make(map[string]TypeFactory)}
|
2024-03-20 16:15:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Types) Register(name string, factory TypeFactory) {
|
2024-03-25 20:31:06 +00:00
|
|
|
t.registry[name] = factory
|
2024-03-20 16:15:27 +00:00
|
|
|
}
|
|
|
|
|
2024-03-20 19:23:31 +00:00
|
|
|
func (t *Types) New(uri string) (Resource, error) {
|
2024-03-25 20:31:06 +00:00
|
|
|
u, e := url.Parse(uri)
|
|
|
|
if u == nil || e != nil {
|
2024-05-24 05:11:51 +00:00
|
|
|
return nil, fmt.Errorf("%w: %s - uri %s", ErrUnknownResourceType, e, uri)
|
2024-03-25 20:31:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if r, ok := t.registry[u.Scheme]; ok {
|
|
|
|
return r(u), nil
|
|
|
|
}
|
|
|
|
return nil, fmt.Errorf("%w: %s", ErrUnknownResourceType, u.Scheme)
|
2024-03-20 19:23:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Types) Has(typename string) bool {
|
2024-03-25 20:31:06 +00:00
|
|
|
if _, ok := t.registry[typename]; ok {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
2024-03-20 16:15:27 +00:00
|
|
|
}
|
2024-04-03 16:54:50 +00:00
|
|
|
|
|
|
|
func (n *TypeName) UnmarshalJSON(b []byte) error {
|
|
|
|
ResourceTypeName := strings.Trim(string(b), "\"")
|
|
|
|
if ResourceTypes.Has(ResourceTypeName) {
|
|
|
|
*n = TypeName(ResourceTypeName)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return fmt.Errorf("%w: %s", ErrUnknownResourceType, ResourceTypeName)
|
|
|
|
}
|