github.com/cnotch/ipchub@v1.1.0/provider/auth/mode.go (about) 1 // Copyright (c) 2019,CAOHONGJU All rights reserved. 2 // Use of this source code is governed by a MIT-style 3 // license that can be found in the LICENSE file. 4 5 package auth 6 7 import ( 8 "bytes" 9 "errors" 10 "fmt" 11 ) 12 13 // Mode 认证模式 14 type Mode int 15 16 // 认证模式常量 17 const ( 18 NoneAuth Mode = iota 19 BasicAuth 20 DigestAuth 21 ) 22 23 var errUnmarshalNilMode = errors.New("can't unmarshal a nil *Mode") 24 25 // String 返回认证模式字串 26 func (m Mode) String() string { 27 switch m { 28 case NoneAuth: 29 return "NONE" 30 case BasicAuth: 31 return "BASIC" 32 case DigestAuth: 33 return "DIGEST" 34 default: 35 return fmt.Sprintf("AuthMode(%d)", m) 36 } 37 } 38 39 // MarshalText 编入认证模式到文本 40 func (m Mode) MarshalText() ([]byte, error) { 41 return []byte(m.String()), nil 42 } 43 44 // UnmarshalText 从文本编出认证模式 45 // 典型的用于 YAML、TOML、JSON等文件编出 46 func (m *Mode) UnmarshalText(text []byte) error { 47 if m == nil { 48 return errUnmarshalNilMode 49 } 50 if !m.unmarshalText(text) && !m.unmarshalText(bytes.ToLower(text)) { 51 return fmt.Errorf("unrecognized Mode: %q", text) 52 } 53 return nil 54 } 55 56 func (m *Mode) unmarshalText(text []byte) bool { 57 switch string(text) { 58 case "none", "NONE", "": // make the zero value useful 59 *m = NoneAuth 60 case "basic", "BASIC": 61 *m = BasicAuth 62 case "digest", "DIGEST": 63 *m = DigestAuth 64 default: 65 return false 66 } 67 return true 68 } 69 70 // Set flag.Value 接口实现. 71 func (m *Mode) Set(s string) error { 72 return m.UnmarshalText([]byte(s)) 73 } 74 75 // Get flag.Getter 接口实现 76 func (m *Mode) Get() interface{} { 77 return *m 78 }