github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/nomad/structs/encoding.go (about)

     1  package structs
     2  
     3  import (
     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
    10  type 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
    14  type nomadJsonEncodingExtensions struct{}
    15  
    16  // ConvertExt calls the registered conversions functions
    17  func (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
    28  func (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.
    33  func NomadJsonEncodingExtensions(h *codec.JsonHandle) *codec.JsonHandle {
    34  	for tpe := range extendedTypes {
    35  		h.SetInterfaceExt(tpe, 1, nomadJsonEncodingExtensions{})
    36  	}
    37  	return h
    38  }