1package structs
2
3import (
4	"reflect"
5
6	"github.com/hashicorp/go-msgpack/codec"
7)
8
9// extendFunc is a mapping from one struct to another, to change the shape of the encoded JSON
10type extendFunc func(interface{}) interface{}
11
12// nomadJsonEncodingExtensions is a catch-all go-msgpack extension
13// it looks up the types in the list of registered extension functions and applies it
14type nomadJsonEncodingExtensions struct{}
15
16// ConvertExt calls the registered conversions functions
17func (n nomadJsonEncodingExtensions) ConvertExt(v interface{}) interface{} {
18	if fn, ok := extendedTypes[reflect.TypeOf(v)]; ok {
19		return fn(v)
20	} else {
21		// shouldn't get here, but returning v will probably result in an infinite loop
22		// return nil and erase this field
23		return nil
24	}
25}
26
27// UpdateExt is required by go-msgpack, but not used by us
28func (n nomadJsonEncodingExtensions) UpdateExt(_ interface{}, _ interface{}) {}
29
30// NomadJsonEncodingExtensions registers all extension functions against the
31// provided JsonHandle.
32// It should be called on any JsonHandle which is used by the API HTTP server.
33func NomadJsonEncodingExtensions(h *codec.JsonHandle) *codec.JsonHandle {
34	for tpe := range extendedTypes {
35		h.SetInterfaceExt(tpe, 1, nomadJsonEncodingExtensions{})
36	}
37	return h
38}
39