-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcode.go
More file actions
48 lines (43 loc) · 1.43 KB
/
code.go
File metadata and controls
48 lines (43 loc) · 1.43 KB
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
47
48
package msgcat
import (
"fmt"
"strconv"
)
// OptionalCode is the optional "code" field for catalog entries. Use it when your project
// already has error or message codes (HTTP statuses, legacy numbers, string ids like "ERR_NOT_FOUND")
// and you want to store that value in the catalog and return it from Message.Code and ErrorCode().
// It can be any value; uniqueness is not enforced. YAML accepts int or string (e.g. code: 404
// or code: "ERR_NOT_FOUND"). In Go use CodeInt or CodeString when building RawMessage.
type OptionalCode string
// UnmarshalYAML allows code to be given as int or string in YAML.
func (c *OptionalCode) UnmarshalYAML(unmarshal func(interface{}) error) error {
var v interface{}
if err := unmarshal(&v); err != nil {
return err
}
if v == nil {
*c = ""
return nil
}
switch t := v.(type) {
case string:
*c = OptionalCode(t)
return nil
case int:
*c = OptionalCode(strconv.Itoa(t))
return nil
case int64:
*c = OptionalCode(strconv.FormatInt(t, 10))
return nil
default:
return fmt.Errorf("code must be string or int, got %T", v)
}
}
// CodeInt returns an OptionalCode from an int (e.g. HTTP status 503). Use when building RawMessage in code.
func CodeInt(i int) OptionalCode {
return OptionalCode(strconv.Itoa(i))
}
// CodeString returns an OptionalCode from a string (e.g. "ERR_NOT_FOUND"). Use when building RawMessage in code.
func CodeString(s string) OptionalCode {
return OptionalCode(s)
}