github.com/sijibomii/docker@v0.0.0-20231230191044-5cf6ca554647/api/client/inspect/inspector_go14.go (about)

     1  // +build !go1.5
     2  
     3  package inspect
     4  
     5  import (
     6  	"bytes"
     7  	"encoding/json"
     8  	"fmt"
     9  	"strings"
    10  )
    11  
    12  // tryeRawInspectFallback executes the inspect template with a raw interface.
    13  // This allows docker cli to parse inspect structs injected with Swarm fields.
    14  // Unfortunately, go 1.4 doesn't fail executing invalid templates when the input is an interface.
    15  // It doesn't allow to modify this behavior either, sending <no value> messages to the output.
    16  // We assume that the template is invalid when there is a <no value>, if the template was valid
    17  // we'd get <nil> or "" values. In that case we fail with the original error raised executing the
    18  // template with the typed input.
    19  func (i *TemplateInspector) tryRawInspectFallback(rawElement []byte, originalErr error) error {
    20  	var raw interface{}
    21  	buffer := new(bytes.Buffer)
    22  	rdr := bytes.NewReader(rawElement)
    23  	dec := json.NewDecoder(rdr)
    24  
    25  	if rawErr := dec.Decode(&raw); rawErr != nil {
    26  		return fmt.Errorf("unable to read inspect data: %v", rawErr)
    27  	}
    28  
    29  	if rawErr := i.tmpl.Execute(buffer, raw); rawErr != nil {
    30  		return fmt.Errorf("Template parsing error: %v", rawErr)
    31  	}
    32  
    33  	if strings.Contains(buffer.String(), "<no value>") {
    34  		return fmt.Errorf("Template parsing error: %v", originalErr)
    35  	}
    36  
    37  	i.buffer.Write(buffer.Bytes())
    38  	i.buffer.WriteByte('\n')
    39  	return nil
    40  }