go-mcm/model/model.go

64 lines
1.2 KiB
Go
Raw Normal View History

2019-10-02 19:03:23 +00:00
package model
import (
"fmt"
2019-11-24 21:20:07 +00:00
"net/url"
"reflect"
2019-10-02 19:03:23 +00:00
"strings"
"git.canopymc.net/Etzelia/go-mcm/model/django"
2019-10-02 19:03:23 +00:00
)
2019-10-03 20:22:22 +00:00
type Model struct {
2019-10-02 19:03:23 +00:00
Token string
URL string
}
2019-10-03 20:22:22 +00:00
func NewModel(token, baseURL string) *Model {
return &Model{
2019-10-02 19:03:23 +00:00
Token: token,
URL: fmt.Sprintf("%s/model", strings.TrimRight(baseURL, "/")),
}
}
2019-10-03 20:22:22 +00:00
func (q *Model) NewDjangoBuilder() *django.Builder {
2019-10-02 19:03:23 +00:00
return django.NewBuilder(q.Token)
}
2019-11-24 21:20:07 +00:00
func (q *Model) endpoint(model string) string {
return fmt.Sprintf("%s/%s/", q.URL, model)
}
func (q *Model) queryEndpoint(model, query string) string {
2019-10-02 19:03:23 +00:00
if !strings.HasPrefix(query, "?") {
query = "?" + query
}
2019-11-24 21:20:07 +00:00
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)
}
2019-10-02 19:03:23 +00:00
}