github.com/blend/go-sdk@v1.20220411.3/selector/check_key.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - 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 selector
     9  
    10  import "unicode/utf8"
    11  
    12  // CheckKey validates a key.
    13  func CheckKey(key string) (err error) {
    14  	keyLen := len(key)
    15  	if keyLen == 0 {
    16  		err = ErrLabelKeyEmpty
    17  		return
    18  	}
    19  	if keyLen > MaxLabelKeyTotalLen {
    20  		err = ErrLabelKeyTooLong
    21  		return
    22  	}
    23  
    24  	var working []rune
    25  	var state int
    26  	var ch rune
    27  	var width int
    28  	// separate the KEY into: DNS_SUBDOMAIN [ "/" DNS_LABEL ]
    29  	for pos := 0; pos < keyLen; pos += width {
    30  		ch, width = utf8.DecodeRuneInString(key[pos:])
    31  		if state == 0 {
    32  			if ch == ForwardSlash {
    33  				err = CheckDNS(string(working))
    34  				if err != nil {
    35  					return
    36  				}
    37  				working = nil
    38  				state = 1
    39  				continue
    40  			}
    41  		}
    42  		working = append(working, ch)
    43  		continue
    44  	}
    45  
    46  	if len(working) == 0 {
    47  		return ErrLabelKeyEmpty
    48  	}
    49  	if len(working) > MaxLabelKeyLen {
    50  		return ErrLabelKeyTooLong
    51  	}
    52  	return CheckName(string(working))
    53  }