Skip to content

Instantly share code, notes, and snippets.

@mix3
Created March 8, 2014 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mix3/9430209 to your computer and use it in GitHub Desktop.
Save mix3/9430209 to your computer and use it in GitHub Desktop.
Callerによるパス解決サンプル
package main
import (
"encoding/json"
"io/ioutil"
"log"
"os"
"path"
"runtime"
)
type Config struct {
Key1 string `json:"key1"`
Key2 string `json:"key2"`
}
var Cfg Config
func main() {
LoadConfigWithCaller("config/config.json")
LoadConfig("config/config.json")
}
func LoadConfig(configPath string) {
log.Printf("loading config file: %s", configPath)
f, err := ioutil.ReadFile(configPath)
if err != nil {
log.Fatal(err)
os.Exit(1)
}
err = json.Unmarshal(f, &Cfg)
if err != nil {
log.Fatal(err)
os.Exit(1)
}
log.Printf("OK")
}
func LoadConfigWithCaller(configPath string) {
_, filename, _, _ := runtime.Caller(1)
path := path.Dir(filename) + "/" + configPath
log.Printf("loading config (with caller) file: %s", path)
f, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal(err)
os.Exit(1)
}
err = json.Unmarshal(f, &Cfg)
if err != nil {
log.Fatal(err)
os.Exit(1)
}
log.Printf("OK")
}
@mix3
Copy link
Author

mix3 commented Mar 8, 2014

$ ./main
2014/03/08 22:00:02 loading config (with caller) file: /private/tmp/caller_sample/config/config.json
2014/03/08 22:00:02 OK
2014/03/08 22:00:02 loading config file: config/config.json
2014/03/08 22:00:02 OK

@mix3
Copy link
Author

mix3 commented Mar 8, 2014

$ cd ..
$ ./caller_sample/main
2014/03/08 22:00:12 loading config (with caller) file: /private/tmp/caller_sample/config/config.json
2014/03/08 22:00:12 OK
2014/03/08 22:00:12 loading config file: config/config.json
2014/03/08 22:00:12 open config/config.json: no such file or directory

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment