dubbo.apache.org/dubbo-go/v3@v3.1.1/cluster/router/condition/matcher/attachment.go (about)

     1  /*
     2   * Licensed to the Apache Software Foundation (ASF) under one or more
     3   * contributor license agreements.  See the NOTICE file distributed with
     4   * this work for additional information regarding copyright ownership.
     5   * The ASF licenses this file to You under the Apache License, Version 2.0
     6   * (the "License"); you may not use this file except in compliance with
     7   * the License.  You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   */
    17  
    18  package matcher
    19  
    20  import (
    21  	"regexp"
    22  	"strings"
    23  )
    24  
    25  import (
    26  	"github.com/dubbogo/gost/log/logger"
    27  )
    28  
    29  import (
    30  	"dubbo.apache.org/dubbo-go/v3/common"
    31  	"dubbo.apache.org/dubbo-go/v3/protocol"
    32  )
    33  
    34  var (
    35  	attachmentPattern       = regexp.MustCompile("attachments\\[([a-zA-Z0-9_]+)\\]")
    36  	notFoundAttachmentValue = "dubbo internal not found attachment condition value"
    37  )
    38  
    39  // AttachmentConditionMatcher analysis the attachments in the rule.
    40  // Examples would be like this:
    41  // "attachments[version]=1.0.0&attachments[timeout]=1000", whenCondition is that the version is equal to '1.0.0' and the timeout is equal to '1000'.
    42  type AttachmentConditionMatcher struct {
    43  	BaseConditionMatcher
    44  }
    45  
    46  func NewAttachmentConditionMatcher(key string) *AttachmentConditionMatcher {
    47  	return &AttachmentConditionMatcher{
    48  		*NewBaseConditionMatcher(key),
    49  	}
    50  }
    51  
    52  func (a *AttachmentConditionMatcher) GetValue(sample map[string]string, url *common.URL, invocation protocol.Invocation) string {
    53  	// split the rule
    54  	expressArray := strings.Split(a.key, "\\.")
    55  	attachmentExpress := expressArray[0]
    56  	matcher := attachmentPattern.FindStringSubmatch(attachmentExpress)
    57  	if len(matcher) == 0 {
    58  		logger.Warn(notFoundAttachmentValue)
    59  		return ""
    60  	}
    61  	// extract the attachment key
    62  	attachmentKey := matcher[1]
    63  	if attachmentKey == "" {
    64  		logger.Warn(notFoundAttachmentValue)
    65  		return ""
    66  	}
    67  	// extract the attachment value
    68  	attachment, _ := invocation.GetAttachment(attachmentKey)
    69  	return attachment
    70  }