commons-go/core/constants/network-port.go
crusader 0fa5fda24d ing
2018-04-28 23:51:47 +09:00

57 lines
864 B
Go

package constants
import (
"encoding/json"
"fmt"
)
type PortType int
const (
PortTypeTCP PortType = iota
PortTypeUDP
)
var (
portTypeID = map[PortType]string{
PortTypeTCP: "tcp",
PortTypeUDP: "udp",
}
portTypeName = map[string]PortType{
"tcp": PortTypeTCP,
"udp": PortTypeUDP,
}
)
func ToPortType(v string) PortType {
return portTypeName[v]
}
func (pt PortType) String() string {
return portTypeID[pt]
}
func (pt PortType) MarshalJSON() ([]byte, error) {
value, ok := portTypeID[pt]
if !ok {
return nil, fmt.Errorf("Invalid EnumType[%s] value", pt)
}
return json.Marshal(value)
}
func (pt PortType) UnmarshalJSON(b []byte) error {
var s string
err := json.Unmarshal(b, &s)
if err != nil {
return err
}
value, ok := portTypeName[s]
if !ok {
return fmt.Errorf("Invalid EnumType[%s] value", s)
}
pt = value
return nil
}