64 lines
1.2 KiB
Go
64 lines
1.2 KiB
Go
package model
|
|
|
|
import (
|
|
"fmt"
|
|
"net/url"
|
|
"reflect"
|
|
"strings"
|
|
|
|
"git.canopymc.net/Etzelia/go-mcm/model/django"
|
|
)
|
|
|
|
type Model struct {
|
|
Token string
|
|
URL string
|
|
}
|
|
|
|
func NewModel(token, baseURL string) *Model {
|
|
return &Model{
|
|
Token: token,
|
|
URL: fmt.Sprintf("%s/model", strings.TrimRight(baseURL, "/")),
|
|
}
|
|
}
|
|
|
|
func (q *Model) NewDjangoBuilder() *django.Builder {
|
|
return django.NewBuilder(q.Token)
|
|
}
|
|
|
|
func (q *Model) endpoint(model string) string {
|
|
return fmt.Sprintf("%s/%s/", q.URL, model)
|
|
}
|
|
|
|
func (q *Model) queryEndpoint(model, query string) string {
|
|
if !strings.HasPrefix(query, "?") {
|
|
query = "?" + query
|
|
}
|
|
return fmt.Sprintf("%s%s", q.endpoint(model), query)
|
|
}
|
|
|
|
func (q *Model) Values(i interface{}) url.Values {
|
|
values := url.Values{}
|
|
values.Set("api", q.Token)
|
|
iVal := reflect.ValueOf(i).Elem()
|
|
typ := iVal.Type()
|
|
for i := 0; i < iVal.NumField(); i++ {
|
|
tag := typ.Field(i).Tag.Get("json")
|
|
if tag != "-" {
|
|
values.Set(strings.ToLower(tag), PyConvert(iVal.Field(i)))
|
|
}
|
|
}
|
|
return values
|
|
}
|
|
|
|
func PyConvert(value reflect.Value) string {
|
|
switch value.Kind() {
|
|
case reflect.Bool:
|
|
if fmt.Sprint(value) == "true" {
|
|
return "True"
|
|
}
|
|
return "False"
|
|
default:
|
|
return fmt.Sprint(value)
|
|
}
|
|
}
|