github.com/minio/console@v1.4.1/pkg/logger/config/bool-flag.go (about) 1 // This file is part of MinIO Console Server 2 // Copyright (c) 2022 MinIO, Inc. 3 // 4 // This program is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Affero General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // This program is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Affero General Public License for more details. 13 // 14 // You should have received a copy of the GNU Affero General Public License 15 // along with this program. If not, see <http://www.gnu.org/licenses/>. 16 17 package config 18 19 import ( 20 "encoding/json" 21 "fmt" 22 "strconv" 23 "strings" 24 ) 25 26 // BoolFlag - wrapper bool type. 27 type BoolFlag bool 28 29 // String - returns string of BoolFlag. 30 func (bf BoolFlag) String() string { 31 if bf { 32 return "on" 33 } 34 35 return "off" 36 } 37 38 // MarshalJSON - converts BoolFlag into JSON data. 39 func (bf BoolFlag) MarshalJSON() ([]byte, error) { 40 return json.Marshal(bf.String()) 41 } 42 43 // UnmarshalJSON - parses given data into BoolFlag. 44 func (bf *BoolFlag) UnmarshalJSON(data []byte) (err error) { 45 var s string 46 if err = json.Unmarshal(data, &s); err == nil { 47 b := BoolFlag(true) 48 if s == "" { 49 // Empty string is treated as valid. 50 *bf = b 51 } else if b, err = ParseBoolFlag(s); err == nil { 52 *bf = b 53 } 54 } 55 56 return err 57 } 58 59 // ParseBool returns the boolean value represented by the string. 60 func ParseBool(str string) (bool, error) { 61 switch str { 62 case "1", "t", "T", "true", "TRUE", "True", "on", "ON", "On": 63 return true, nil 64 case "0", "f", "F", "false", "FALSE", "False", "off", "OFF", "Off": 65 return false, nil 66 } 67 if strings.EqualFold(str, "enabled") { 68 return true, nil 69 } 70 if strings.EqualFold(str, "disabled") { 71 return false, nil 72 } 73 return false, fmt.Errorf("ParseBool: parsing '%s': %w", str, strconv.ErrSyntax) 74 } 75 76 // ParseBoolFlag - parses string into BoolFlag. 77 func ParseBoolFlag(s string) (bf BoolFlag, err error) { 78 b, err := ParseBool(s) 79 return BoolFlag(b), err 80 }