-
Notifications
You must be signed in to change notification settings - Fork 10
/
models.go
70 lines (59 loc) · 1.67 KB
/
models.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package authn
import (
"fmt"
"strings"
)
// Account is an AuthN user account
type Account struct {
ID int `json:"id"`
Username string `json:"username"`
Locked bool `json:"locked"`
Deleted bool `json:"deleted"`
}
// FieldError is a returned for each field in an API
// request that does not match the expectations. Examples
// are MISSING, TAKEN, INSECURE, ...
type FieldError struct {
Field string `json:"field"`
Message string `json:"message"`
}
// String returns a string representation of f
// and implements fmt.Stringer
func (f FieldError) String() string {
return fmt.Sprintf("%s: %s", f.Field, f.Message)
}
// ErrorResponse is returned together with 4xx and 5xx HTTP status
// codes and contains a list of error conditions encountered while
// processing an API request
// It implements the error interface
type ErrorResponse struct {
StatusCode int `json:"-"`
URL string `json:"-"`
Errors []FieldError `json:"errors"`
}
// Error implements the error interface
func (e *ErrorResponse) Error() string {
msgs := make([]string, len(e.Errors))
for idx, field := range e.Errors {
msgs[idx] = field.String()
}
return fmt.Sprintf("received %d from %s. Errors in %s", e.StatusCode, e.URL, strings.Join(msgs, "; "))
}
// HasField returns true if field caused an error
func (e *ErrorResponse) HasField(field string) bool {
for _, f := range e.Errors {
if f.Field == field {
return true
}
}
return false
}
// Field returns the error message for field if any
func (e *ErrorResponse) Field(field string) (string, bool) {
for _, f := range e.Errors {
if f.Field == field {
return f.Message, true
}
}
return "", false
}