github.com/hernad/nomad@v1.6.112/nomad/structs/encoding.go (about)

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