github.com/cloudwego/kitex@v0.9.0/pkg/utils/yaml.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 utils
    18  
    19  import (
    20  	"io/ioutil"
    21  	"os"
    22  	"time"
    23  
    24  	"gopkg.in/yaml.v3"
    25  
    26  	"github.com/cloudwego/kitex/internal/configutil"
    27  )
    28  
    29  var (
    30  	_ configutil.Config         = &YamlConfig{}
    31  	_ configutil.RichTypeConfig = &YamlConfig{}
    32  )
    33  
    34  // YamlConfig contains configurations from yaml file.
    35  type YamlConfig struct {
    36  	configutil.RichTypeConfig
    37  	data map[interface{}]interface{}
    38  }
    39  
    40  // ReadYamlConfigFile creates a YamlConfig from the file.
    41  func ReadYamlConfigFile(yamlFile string) (*YamlConfig, error) {
    42  	fd, err := os.Open(yamlFile)
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  	defer fd.Close()
    47  
    48  	b, err := ioutil.ReadAll(fd)
    49  	if err != nil {
    50  		return nil, err
    51  	}
    52  
    53  	data := make(map[interface{}]interface{})
    54  	err = yaml.Unmarshal(b, &data)
    55  	if err != nil {
    56  		return nil, err
    57  	}
    58  
    59  	y := &YamlConfig{data: data}
    60  	y.RichTypeConfig = configutil.NewRichTypeConfig(y)
    61  	return y, nil
    62  }
    63  
    64  // Get implements the configutil.Config interface.
    65  func (yc *YamlConfig) Get(key string) (interface{}, bool) {
    66  	val, ok := yc.data[key]
    67  	return val, ok
    68  }
    69  
    70  // GetDuration implements the configutil.RichTypeConfig interface.
    71  // It converts string item to time.Duration.
    72  func (yc *YamlConfig) GetDuration(key string) (time.Duration, bool) {
    73  	if s, ok := yc.data[key].(string); ok {
    74  		val, err := time.ParseDuration(s)
    75  		if err != nil {
    76  			return 0, false
    77  		}
    78  		return val, true
    79  	}
    80  	return 0, false
    81  }