Created
March 8, 2014 12:58
-
-
Save mix3/9430209 to your computer and use it in GitHub Desktop.
Callerによるパス解決サンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} |
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