add(system): resource type and encoding

This commit is contained in:
Tit Petric
2019-02-05 14:41:57 +01:00
parent c5a0015963
commit d105adfed6
2 changed files with 72 additions and 0 deletions
+39
View File
@@ -0,0 +1,39 @@
package types
import (
"fmt"
"encoding/json"
)
type Resource struct {
ID uint64 `json:"id,string"`
Name string `json:"name"`
Scope string `json:"scope"`
}
type ResourceJSON struct {
ID uint64 `json:"id,string"`
Name string `json:"name"`
Scope string `json:"scope"`
ResourceID string `json:"resource"`
}
func (r Resource) String() string {
return fmt.Sprintf("%s:%d", r.Scope, r.ID)
}
func (r Resource) All() string {
return fmt.Sprintf("%s:*", r.Scope)
}
func (r Resource) MarshalJSON() ([]byte, error) {
return json.Marshal(ResourceJSON{
r.ID,
r.Name,
r.Scope,
r.String(),
})
}
var _ fmt.Stringer = Resource{}
+33
View File
@@ -0,0 +1,33 @@
package types
import (
"fmt"
"testing"
"encoding/json"
"github.com/crusttech/crust/internal/test"
)
func TestResource(t *testing.T) {
var (
assert = test.Assert
)
r := Resource{123, "Test name", "team"}
assert(t, r.String() == "team:123", "Resource ID doesn't match, team:123 != '%s'", r.String())
b, _ := json.Marshal(r)
fmt.Println(string(b))
{
r := ResourceJSON{}
json.Unmarshal(b, &r)
assert(t, r.ResourceID == "team:123", "Decoded full-json resource ID doesn't match, team:123 != '%s'", r.ResourceID)
}
{
r := Resource{}
json.Unmarshal(b, &r)
assert(t, r.String() == "team:123", "Decoded full-json resource ID doesn't match, team:123 != '%s'", r.String())
}
}