Configuration Control
Golf comes with a built-in JSON configuration parser. You can create an empty configuration by calling golf.NewConfig()
. Moreover, you can read the configuration directly from a JSON file:
package main
import (
"github.com/dinever/golf"
"os"
)
func versionHandler(ctx *golf.Context) {
appVersion, _ := ctx.App.Config.GetString("APP/VERSION", "unavailable")
ctx.Send(appVersion)
}
func homeHandler(ctx *golf.Context) {
apiKey, _ := ctx.App.Config.GetString("API_KEY", "0")
ctx.Send(apiKey)
}
func main() {
file, err := os.Open("config.json")
if err != nil {
panic(err)
}
app := golf.New()
app.Get("/version", versionHandler)
app.Get("/", homeHandler)
app.Config, err = golf.ConfigFromJSON(file)
app.Run(":9000")
}
{
"API_KEY": "e5c9b7101a9ac541615a73e99636ba1c",
"APP": {
"VERSION": "0.1.0"
}
}
You can look up a child node in the JSON map by using slash(/) in the key as the above code did in the versionHandler
.
The above code is also available at github.com/dinever/golf/tree/master/examples/config_control.
Updated less than a minute ago