加载json相对来说比较简单,不需要第三方包,用内置os包即可
config.json
{
"app_name": "my_project",
"env": ["dev", "test", "product"],
"app": {
"path": "/www/root"
},
"mysql": {
"host": "127.0.0.1",
"name": "root",
"password": "123456",
"port": 3306
}
}
main.go
package main
import (
"encoding/json"
"fmt"
"log"
"os"
)
type Config struct {
AppName string `json:"app_name"`
Env []string
App *App
Mysql *Mysql
}
type App struct {
Path string
}
type Mysql struct {
Host string
Name string
Password string
Port int16
}
func main() {
file, _ := os.Open("config.json")
defer file.Close()
decoder := json.NewDecoder(file)
var c Config
err := decoder.Decode(&c)
if err != nil {
log.Fatal(err)
return
}
fmt.Printf("%s, %v, %v, %v", c.AppName, c.Env, c.App, c.Mysql)
}