-
Notifications
You must be signed in to change notification settings - Fork 21
/
types.go
74 lines (64 loc) · 1.75 KB
/
types.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
71
72
73
74
package sshutil
import (
"encoding/json"
"strings"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
)
// CertType defines the certificate type, it can be a user or a host
// certificate.
type CertType uint32
const (
// UserCert defines a user certificate.
UserCert CertType = ssh.UserCert
// HostCert defines a host certificate.
HostCert CertType = ssh.HostCert
)
const (
userString = "user"
hostString = "host"
)
// CertTypeFromString returns the CertType for the string "user" and "host".
func CertTypeFromString(s string) (CertType, error) {
switch strings.ToLower(s) {
case userString:
return UserCert, nil
case hostString:
return HostCert, nil
default:
return 0, errors.Errorf("unknown certificate type '%s'", s)
}
}
// String returns "user" for user certificates and "host" for host certificates.
// It will return the empty string for any other value.
func (c CertType) String() string {
switch c {
case UserCert:
return userString
case HostCert:
return hostString
default:
return ""
}
}
// MarshalJSON implements the json.Marshaler interface for CertType. UserCert
// will be marshaled as the string "user" and HostCert as "host".
func (c CertType) MarshalJSON() ([]byte, error) {
if s := c.String(); s != "" {
return []byte(`"` + s + `"`), nil
}
return nil, errors.Errorf("unknown certificate type %d", c)
}
// UnmarshalJSON implements the json.Unmarshaler interface for CertType.
func (c *CertType) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return errors.Wrap(err, "error unmarshaling certificate type")
}
certType, err := CertTypeFromString(s)
if err != nil {
return errors.Errorf("error unmarshaling '%s' as a certificate type", s)
}
*c = certType
return nil
}