github.com/sacloud/iaas-api-go@v1.12.0/types/string_flag.go (about)

     1  // Copyright 2022-2023 The sacloud/iaas-api-go Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package types
    16  
    17  import (
    18  	"strings"
    19  )
    20  
    21  var trueStrings = []string{"true", "on", "1"}
    22  
    23  var (
    24  	// StringTrue true値
    25  	StringTrue = StringFlag(true)
    26  	// StringFalse false値
    27  	StringFalse = StringFlag(false)
    28  )
    29  
    30  // StringFlag bool型のラッパー、文字列(true/false/on/off/1/0)などをbool値として扱う
    31  //
    32  // - 大文字/小文字の区別はしない
    33  // - 空文字だった場合はfalse
    34  // - 小文字にした場合に次のいずれかにマッチしない場合はfalse [ true / on / 1 ]
    35  type StringFlag bool
    36  
    37  // String StringFlagの文字列表現
    38  func (f *StringFlag) String() string {
    39  	if f.Bool() {
    40  		return "True"
    41  	}
    42  	return "False"
    43  }
    44  
    45  // Bool StringFlagのbool表現
    46  func (f *StringFlag) Bool() bool {
    47  	return f != nil && bool(*f)
    48  }
    49  
    50  // MarshalJSON 文字列でのJSON出力に対応するためのMarshalJSON実装
    51  func (f *StringFlag) MarshalJSON() ([]byte, error) {
    52  	if f != nil && bool(*f) {
    53  		return []byte(`"True"`), nil
    54  	}
    55  	return []byte(`"False"`), nil
    56  }
    57  
    58  // UnmarshalJSON 文字列に対応するためのUnmarshalJSON実装
    59  func (f *StringFlag) UnmarshalJSON(b []byte) error {
    60  	s := strings.ReplaceAll(strings.ToLower(string(b)), `"`, ``)
    61  	res := false
    62  	for _, strTrue := range trueStrings {
    63  		if s == strTrue {
    64  			res = true
    65  			break
    66  		}
    67  	}
    68  	*f = StringFlag(res)
    69  	return nil
    70  }