github.com/grpc-ecosystem/grpc-gateway/v2@v2.19.1/protoc-gen-openapiv2/internal/genopenapi/format.go (about)

     1  package genopenapi
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"io"
     7  
     8  	"gopkg.in/yaml.v3"
     9  )
    10  
    11  type Format string
    12  
    13  const (
    14  	FormatJSON Format = "json"
    15  	FormatYAML Format = "yaml"
    16  )
    17  
    18  type ContentEncoder interface {
    19  	Encode(v interface{}) (err error)
    20  }
    21  
    22  func (f Format) Validate() error {
    23  	switch f {
    24  	case FormatJSON, FormatYAML:
    25  		return nil
    26  	default:
    27  		return errors.New("unknown format: " + string(f))
    28  	}
    29  }
    30  
    31  func (f Format) NewEncoder(w io.Writer) (ContentEncoder, error) {
    32  	switch f {
    33  	case FormatYAML:
    34  		enc := yaml.NewEncoder(w)
    35  		enc.SetIndent(2)
    36  
    37  		return enc, nil
    38  	case FormatJSON:
    39  		enc := json.NewEncoder(w)
    40  		enc.SetIndent("", "  ")
    41  
    42  		return enc, nil
    43  	default:
    44  		return nil, errors.New("unknown format: " + string(f))
    45  	}
    46  }