github.com/google/cloudprober@v0.11.3/validators/regex/regex.go (about)

     1  // Copyright 2018 The Cloudprober 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 regex provides regex validator for the Cloudprober's
    16  // validator framework.
    17  package regex
    18  
    19  import (
    20  	"errors"
    21  	"fmt"
    22  	"regexp"
    23  
    24  	"github.com/google/cloudprober/logger"
    25  )
    26  
    27  // Validator implements a regex validator.
    28  type Validator struct {
    29  	r *regexp.Regexp
    30  	l *logger.Logger
    31  }
    32  
    33  // Init initializes the regex validator.
    34  // It compiles the regex in the configuration and returns an error if regex
    35  // doesn't compile for some reason.
    36  func (v *Validator) Init(config interface{}, l *logger.Logger) error {
    37  	regexStr, ok := config.(string)
    38  	if !ok {
    39  		return fmt.Errorf("%v is not a valid regex validator config", config)
    40  	}
    41  	if regexStr == "" {
    42  		return errors.New("validator regex string cannot be empty")
    43  	}
    44  
    45  	r, err := regexp.Compile(regexStr)
    46  	if err != nil {
    47  		return fmt.Errorf("error compiling the given regex (%s): %v", regexStr, err)
    48  	}
    49  
    50  	v.r = r
    51  	v.l = l
    52  	return nil
    53  }
    54  
    55  // Validate the provided responseBody and return true if responseBody matches
    56  // the configured regex.
    57  func (v *Validator) Validate(responseBody []byte) (bool, error) {
    58  	return v.r.Match(responseBody), nil
    59  }