github.com/cloudwego/kitex@v0.9.0/pkg/generic/descriptor/field_mapping.go (about)

     1  /*
     2   * Copyright 2021 CloudWeGo Authors
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package descriptor
    18  
    19  import (
    20  	"reflect"
    21  	"regexp"
    22  	"strings"
    23  )
    24  
    25  var escape = regexp.MustCompile(`\\.`)
    26  
    27  // FiledMapping mapping handle for filed descriptor
    28  type FiledMapping interface {
    29  	Handle(field *FieldDescriptor)
    30  }
    31  
    32  // NewFieldMapping FiledMapping creator
    33  type NewFieldMapping func(value string) FiledMapping
    34  
    35  // GoTagAnnatition go.tag annatation define
    36  var GoTagAnnatition = NewBAMAnnotation("go.tag", NewGoTag)
    37  
    38  // go.tag = 'json:"xx"'
    39  type goTag struct {
    40  	tag reflect.StructTag
    41  }
    42  
    43  // NewGoTag go.tag annotation creator
    44  var NewGoTag NewFieldMapping = func(value string) FiledMapping {
    45  	value = escape.ReplaceAllStringFunc(value, func(m string) string {
    46  		if m[1] == '"' {
    47  			return m[1:]
    48  		}
    49  		return m
    50  	})
    51  	return &goTag{reflect.StructTag(value)}
    52  }
    53  
    54  func (m *goTag) Handle(field *FieldDescriptor) {
    55  	tag := m.tag.Get("json")
    56  	if idx := strings.Index(tag, ","); idx != -1 {
    57  		field.Alias = tag[:idx]
    58  	} else {
    59  		field.Alias = tag
    60  	}
    61  }