json_utility.go 1.56 KB
package restutility

import (
	"net/http"
	"strings"
)

const APIVersion "/api/v1"

type LangMap map[string]map[string]string

type Field struct {
	Parameter  string `json:"param"`
	Type       string `json:"type"`
	Visible    bool   `json:"visible"`
	Editable   bool   `json:"editable"`
}

type JSONParams struct {
	Lang    LangMap
	Fields  []Field
	IdField string
	Correlations []CorrelationField `json:"correlation_fields"`
}

type JSONPayload struct {
	Method	     string             `json:"method"`
	Params	     map[string]string  `json:"params"`
	Lang	     LangMap            `json:"lang"`
	Fields	     []Field            `json:"fields"`
	Correlations []CorrelationField `json:"correlation_fields"`
	IdField      string             `json:"idField"`
	// Data can only hold slices of any type. It can't be used for itteration
	Data	     interface{}        `json:"data"`
}

func NewJSONParams(lang LangMap,
	fields []Field,
	id string,
	correlations []CorrelationField) JSONParams {

	var jp JSONParams

	jp.Lang = lang
	jp.Fields = fields
	jp.IdField = id
	jp.Correlations = correlations

	return jp
}

func NewJSONPayload(r *http.Request, params JSONParams) JSONPayload {
	var obj JSONPayload
	obj.Method = strings.ToLower(r.Method + " " + r.URL.Path)
	obj.Params = make(map[string]string, 0)
	obj.Lang = make(map[string]map[string]string, 0)
	obj.Fields = make([]Field, 0)
	obj.IdField = params.IdField
	obj.Correlations = params.Correlations

	for k, m := range params.Lang {
		obj.Lang[k] = m
	}
	for _, f := range params.Fields {
		obj.Fields = append(obj.Fields, f)
	}

	return obj
}