summaryrefslogtreecommitdiff
path: root/pkg/api/handlers/decoder.go
blob: d87409394fa0afaf57121bd32deee1b243ab074b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package handlers

import (
	"encoding/json"
	"reflect"
	"time"

	"github.com/gorilla/schema"
	"github.com/sirupsen/logrus"
)

// NewAPIDecoder returns a configured schema.Decoder
func NewAPIDecoder() *schema.Decoder {
	d := schema.NewDecoder()
	d.IgnoreUnknownKeys(true)
	d.RegisterConverter(map[string][]string{}, convertUrlValuesString)
	d.RegisterConverter(time.Time{}, convertTimeString)
	return d
}

// On client:
// 	v := map[string][]string{
//		"dangling": {"true"},
//	}
//
//	payload, err := jsoniter.MarshalToString(v)
//	if err != nil {
//		panic(err)
//	}
//	payload = url.QueryEscape(payload)
func convertUrlValuesString(query string) reflect.Value {
	f := map[string][]string{}

	err := json.Unmarshal([]byte(query), &f)
	if err != nil {
		logrus.Infof("convertUrlValuesString: Failed to Unmarshal %s: %s", query, err.Error())
	}

	return reflect.ValueOf(f)
}

func convertTimeString(query string) reflect.Value {
	t, err := time.Parse(time.RFC3339, query)
	if err != nil {
		logrus.Infof("convertTimeString: Failed to Unmarshal %s: %s", query, err.Error())

		return reflect.ValueOf(time.Time{})
	}
	return reflect.ValueOf(t)
}