File: example_test.go

package info (click to toggle)
golang-github-shibukawa-configdir 0.0~git20170330.e180dbd-1.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid, trixie
  • size: 92 kB
  • sloc: makefile: 8
file content (70 lines) | stat: -rw-r--r-- 1,661 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package configdir_test

import (
	"encoding/json"
	"github.com/shibukawa/configdir"
	"io/ioutil"
	"log"
	"net/http"
	"path/filepath"
)

type Config struct {
	UserName string `json:"user-name"`
}

var DefaultConfig = Config{
	UserName: "baron", // Do you remember BeOS?
}

// Sample for reading configuration
func ExampleConfigDir() {

	var config Config

	configDirs := configdir.New("vendor-name", "application-name")
	// optional: local path has the highest priority
	configDirs.LocalPath, _ = filepath.Abs(".")
	folder := configDirs.QueryFolderContainsFile("setting.json")
	if folder != nil {
		data, _ := folder.ReadFile("setting.json")
		json.Unmarshal(data, &config)
	} else {
		config = DefaultConfig
	}
}

// Sample for reading configuration
func ExampleConfigDir_QueryFolders() {
	configDirs := configdir.New("vendor-name", "application-name")

	var config Config
	data, _ := json.Marshal(&config)

	// Stores to local folder
	folders := configDirs.QueryFolders(configdir.Local)
	folders[0].WriteFile("setting.json", data)

	// Stores to user folder
	folders = configDirs.QueryFolders(configdir.Global)
	folders[0].WriteFile("setting.json", data)

	// Stores to system folder
	folders = configDirs.QueryFolders(configdir.System)
	folders[0].WriteFile("setting.json", data)
}

// Sample for getting cache folder
func ExampleConfigDir_QueryCacheFolder() {
	configDirs := configdir.New("vendor-name", "application-name")
	cache := configDirs.QueryCacheFolder()

	resp, err := http.Get("http://examples.com/sdk.zip")
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	cache.WriteFile("sdk.zip", body)
}