2023-04-10 15:36:59 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2021-04-02 13:31:10 +00:00
|
|
|
package structs
|
2021-02-11 15:40:59 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"reflect"
|
|
|
|
|
2023-05-01 21:18:34 +00:00
|
|
|
"github.com/hashicorp/go-msgpack/codec"
|
2021-02-11 15:40:59 +00:00
|
|
|
)
|
|
|
|
|
2021-03-23 18:18:51 +00:00
|
|
|
// extendFunc is a mapping from one struct to another, to change the shape of the encoded JSON
|
2021-03-22 01:49:21 +00:00
|
|
|
type extendFunc func(interface{}) interface{}
|
|
|
|
|
2021-03-23 18:18:51 +00:00
|
|
|
// nomadJsonEncodingExtensions is a catch-all go-msgpack extension
|
|
|
|
// it looks up the types in the list of registered extension functions and applies it
|
2021-03-22 01:49:21 +00:00
|
|
|
type nomadJsonEncodingExtensions struct{}
|
|
|
|
|
|
|
|
// ConvertExt calls the registered conversions functions
|
|
|
|
func (n nomadJsonEncodingExtensions) ConvertExt(v interface{}) interface{} {
|
|
|
|
if fn, ok := extendedTypes[reflect.TypeOf(v)]; ok {
|
|
|
|
return fn(v)
|
|
|
|
} else {
|
2021-03-23 18:13:10 +00:00
|
|
|
// shouldn't get here, but returning v will probably result in an infinite loop
|
|
|
|
// return nil and erase this field
|
|
|
|
return nil
|
2021-03-22 01:49:21 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-23 18:18:51 +00:00
|
|
|
// UpdateExt is required by go-msgpack, but not used by us
|
2021-03-22 01:49:21 +00:00
|
|
|
func (n nomadJsonEncodingExtensions) UpdateExt(_ interface{}, _ interface{}) {}
|
2021-02-11 15:40:59 +00:00
|
|
|
|
2021-03-23 18:18:51 +00:00
|
|
|
// NomadJsonEncodingExtensions registers all extension functions against the
|
|
|
|
// provided JsonHandle.
|
|
|
|
// It should be called on any JsonHandle which is used by the API HTTP server.
|
2021-03-22 01:49:21 +00:00
|
|
|
func NomadJsonEncodingExtensions(h *codec.JsonHandle) *codec.JsonHandle {
|
2021-03-22 14:12:42 +00:00
|
|
|
for tpe := range extendedTypes {
|
2021-03-22 01:49:21 +00:00
|
|
|
h.SetInterfaceExt(tpe, 1, nomadJsonEncodingExtensions{})
|
|
|
|
}
|
2021-02-11 15:40:59 +00:00
|
|
|
return h
|
|
|
|
}
|