github.com/wangyougui/gf/v2@v2.6.5/os/gcfg/gcfg_z_example_test.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/wangyougui/gf.
     6  
     7  package gcfg_test
     8  
     9  import (
    10  	"fmt"
    11  	"os"
    12  
    13  	"github.com/wangyougui/gf/v2/frame/g"
    14  	"github.com/wangyougui/gf/v2/os/gcfg"
    15  	"github.com/wangyougui/gf/v2/os/gcmd"
    16  	"github.com/wangyougui/gf/v2/os/gctx"
    17  	"github.com/wangyougui/gf/v2/os/genv"
    18  )
    19  
    20  func ExampleConfig_GetWithEnv() {
    21  	var (
    22  		key = `ENV_TEST`
    23  		ctx = gctx.New()
    24  	)
    25  	v, err := g.Cfg().GetWithEnv(ctx, key)
    26  	if err != nil {
    27  		panic(err)
    28  	}
    29  	fmt.Printf("env:%s\n", v)
    30  	if err = genv.Set(key, "gf"); err != nil {
    31  		panic(err)
    32  	}
    33  	v, err = g.Cfg().GetWithEnv(ctx, key)
    34  	if err != nil {
    35  		panic(err)
    36  	}
    37  	fmt.Printf("env:%s", v)
    38  
    39  	// Output:
    40  	// env:
    41  	// env:gf
    42  }
    43  
    44  func ExampleConfig_GetWithCmd() {
    45  	var (
    46  		key = `cmd.test`
    47  		ctx = gctx.New()
    48  	)
    49  	v, err := g.Cfg().GetWithCmd(ctx, key)
    50  	if err != nil {
    51  		panic(err)
    52  	}
    53  	fmt.Printf("cmd:%s\n", v)
    54  	// Re-Initialize custom command arguments.
    55  	os.Args = append(os.Args, fmt.Sprintf(`--%s=yes`, key))
    56  	gcmd.Init(os.Args...)
    57  	// Retrieve the configuration and command option again.
    58  	v, err = g.Cfg().GetWithCmd(ctx, key)
    59  	if err != nil {
    60  		panic(err)
    61  	}
    62  	fmt.Printf("cmd:%s", v)
    63  
    64  	// Output:
    65  	// cmd:
    66  	// cmd:yes
    67  }
    68  
    69  func Example_NewWithAdapter() {
    70  	var (
    71  		ctx          = gctx.New()
    72  		content      = `{"a":"b", "c":1}`
    73  		adapter, err = gcfg.NewAdapterContent(content)
    74  	)
    75  	if err != nil {
    76  		panic(err)
    77  	}
    78  	config := gcfg.NewWithAdapter(adapter)
    79  	fmt.Println(config.MustGet(ctx, "a"))
    80  	fmt.Println(config.MustGet(ctx, "c"))
    81  
    82  	// Output:
    83  	// b
    84  	// 1
    85  }