-
Notifications
You must be signed in to change notification settings - Fork 2
/
preflight.go
43 lines (34 loc) · 779 Bytes
/
preflight.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
package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/ghodss/yaml"
"unicode/utf8"
)
// ensure YAML as well as JSON can be read
// applies only to file-based processing; the server only accepts JSON
func preflightAsset(a *[]byte) error {
if len(*a) == 0 {
return errors.New("input must not be empty")
}
if utf8.Valid(*a) == false {
return errors.New("input must be valid UTF-8")
}
// attempt to parse JSON first
var any interface{}
err := json.Unmarshal(*a, &any)
// input is valid JSON
if err == nil {
return nil
}
jsonError := err
// not JSON
json, err := yaml.YAMLToJSON(*a)
if err != nil {
return errors.New(fmt.Sprintf("invalid JSON: %v; invalid YAML: %v", jsonError, err))
}
// successful conversion
*a = json
return nil
}