• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
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
16package utils
17
18import (
19	"github.com/Unknwon/goconfig"
20	"github.com/sirupsen/logrus"
21	"reflect"
22	"strings"
23)
24
25// ParseFromConfigFile parse ini file and set values by the tag of fields.
26// 'p' must be a pointer to the given structure, otherwise will panic.
27// Only process its string fields and its sub structs.
28func ParseFromConfigFile(section string, p any) {
29	conf, err := goconfig.LoadConfigFile("fotff.ini")
30	if err != nil {
31		logrus.Warnf("load config file err: %v", err)
32	}
33	rv := reflect.ValueOf(p)
34	rt := reflect.TypeOf(p)
35	for i := 0; i < rv.Elem().NumField(); i++ {
36		switch rt.Elem().Field(i).Type.Kind() {
37		case reflect.String:
38			key := rt.Elem().Field(i).Tag.Get("key")
39			if key == "" {
40				continue
41			}
42			var v string
43			if conf != nil {
44				v, err = conf.GetValue(section, key)
45			}
46			if conf == nil || err != nil {
47				v = rt.Elem().Field(i).Tag.Get("default")
48			}
49			rv.Elem().Field(i).SetString(v)
50		case reflect.Slice:
51			if rt.Elem().Field(i).Type.Elem().Kind() != reflect.String {
52				break
53			}
54			key := rt.Elem().Field(i).Tag.Get("key")
55			if key == "" {
56				continue
57			}
58			var v string
59			if conf != nil {
60				v, err = conf.GetValue(section, key)
61			}
62			if conf == nil || err != nil {
63				v = rt.Elem().Field(i).Tag.Get("default")
64			}
65			rv.Elem().Field(i).Set(reflect.ValueOf(strings.Split(v, ",")))
66		case reflect.Struct:
67			ParseFromConfigFile(section, rv.Elem().Field(i).Addr().Interface())
68		}
69	}
70}
71