github.com/blend/go-sdk@v1.20220411.3/examples/configutil/main.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package main
     9  
    10  import (
    11  	"context"
    12  	"flag"
    13  	"fmt"
    14  
    15  	"github.com/blend/go-sdk/configutil"
    16  	"github.com/blend/go-sdk/logger"
    17  	"github.com/blend/go-sdk/ref"
    18  )
    19  
    20  var (
    21  	flagTarget      = flag.String("target", "", "The target URL")
    22  	flagEnvironment = flag.String("env", "", "The current environment")
    23  )
    24  
    25  // Config is a sample config.
    26  type Config struct {
    27  	Target       string `yaml:"target"`
    28  	DebugEnabled *bool  `yaml:"debugEnabled"`
    29  	MaxCount     int    `yaml:"maxCount"`
    30  	Environment  string `yaml:"env"`
    31  }
    32  
    33  // Resolve parses the config and sets values from predefined sources.
    34  func (c *Config) Resolve(ctx context.Context) error {
    35  	return configutil.Resolve(ctx,
    36  		configutil.SetString(&c.Target,
    37  			configutil.String(*flagTarget),
    38  			configutil.Env("TARGET"),
    39  			configutil.String(c.Target),
    40  			configutil.String("https://google.com/robots.txt"),
    41  		),
    42  		configutil.SetBoolPtr(&c.DebugEnabled,
    43  			configutil.Env("DEBUG_ENABLED"),
    44  			configutil.Bool(c.DebugEnabled),
    45  			configutil.Bool(ref.Bool(true)),
    46  		),
    47  		configutil.SetInt(&c.MaxCount,
    48  			configutil.Int(c.MaxCount),
    49  			configutil.Env("MAX_COUNT"),
    50  			configutil.Int(10),
    51  		),
    52  		configutil.SetString(&c.Environment,
    53  			configutil.String(*flagEnvironment),
    54  			configutil.Env("SERVICE_ENV"),
    55  			configutil.String(c.Environment),
    56  			configutil.String("development"),
    57  		),
    58  	)
    59  }
    60  
    61  var (
    62  	_ configutil.Resolver = (*Config)(nil)
    63  )
    64  
    65  func main() {
    66  	flag.Parse()
    67  	log := logger.All().WithPath("config")
    68  	config := new(Config)
    69  	if _, err := configutil.Read(config,
    70  		configutil.OptLog(log),
    71  	); !configutil.IsIgnored(err) {
    72  		logger.FatalExit(err)
    73  	}
    74  	fmt.Println("target:", config.Target)
    75  	fmt.Println("debug enabled:", *config.DebugEnabled)
    76  	fmt.Println("env:", config.Environment)
    77  }