github.com/blend/go-sdk@v1.20240719.1/stringutil/parse_bool.go (about)

     1  /*
     2  
     3  Copyright (c) 2024 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package stringutil
     9  
    10  import (
    11  	"strings"
    12  
    13  	"github.com/blend/go-sdk/ex"
    14  )
    15  
    16  // Error Constants
    17  const (
    18  	ErrInvalidBoolValue ex.Class = "invalid bool value"
    19  )
    20  
    21  // MustParseBool parses a boolean value and panics if there is an error.
    22  func MustParseBool(str string) bool {
    23  	boolValue, err := ParseBool(str)
    24  	if err != nil {
    25  		panic(err)
    26  	}
    27  	return boolValue
    28  }
    29  
    30  // ParseBool parses a given string as a boolean value.
    31  func ParseBool(str string) (bool, error) {
    32  	strLower := strings.ToLower(strings.TrimSpace(str))
    33  	switch strLower {
    34  	case "true", "t", "1", "yes", "y", "enabled", "on":
    35  		return true, nil
    36  	case "false", "f", "0", "no", "n", "disabled", "off":
    37  		return false, nil
    38  	}
    39  	return false, ex.New(ErrInvalidBoolValue, ex.OptMessage(str))
    40  }