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