File: config_props.go

package info (click to toggle)
golang-github-nicholas-fedor-shoutrrr 0.8.18-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 4,328 kB
  • sloc: sh: 61; makefile: 5
file content (49 lines) | stat: -rw-r--r-- 1,314 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package format

import (
	"errors"
	"fmt"
	"reflect"

	"github.com/nicholas-fedor/shoutrrr/pkg/types"
)

var ErrNotConfigProp = errors.New("struct field cannot be used as a prop")

// GetConfigPropFromString deserializes a config property from a string representation using the ConfigProp interface.
func GetConfigPropFromString(structType reflect.Type, value string) (reflect.Value, error) {
	valuePtr := reflect.New(structType)

	configProp, ok := valuePtr.Interface().(types.ConfigProp)
	if !ok {
		return reflect.Value{}, ErrNotConfigProp
	}

	if err := configProp.SetFromProp(value); err != nil {
		return reflect.Value{}, fmt.Errorf("failed to set config prop from string: %w", err)
	}

	return valuePtr, nil
}

// GetConfigPropString serializes a config property to a string representation using the ConfigProp interface.
func GetConfigPropString(propPtr reflect.Value) (string, error) {
	if propPtr.Kind() != reflect.Ptr {
		propVal := propPtr
		propPtr = reflect.New(propVal.Type())
		propPtr.Elem().Set(propVal)
	}

	if propPtr.CanInterface() {
		if configProp, ok := propPtr.Interface().(types.ConfigProp); ok {
			s, err := configProp.GetPropValue()
			if err != nil {
				return "", fmt.Errorf("failed to get config prop string: %w", err)
			}

			return s, nil
		}
	}

	return "", ErrNotConfigProp
}