Skip to content

Instantly share code, notes, and snippets.

@aquiseb
Last active May 1, 2018 07:12
Show Gist options
  • Save aquiseb/fb566947aff468e04d15921a38426009 to your computer and use it in GitHub Desktop.
Save aquiseb/fb566947aff468e04d15921a38426009 to your computer and use it in GitHub Desktop.
Go Friendly Configs
#! /bin/bash
# ------------------------------------------------------------
# Downloads required packages
# ------------------------------------------------------------
# Realize is a Golang Task Runner performing live reloading
if [ ! -f $GOPATH/bin/realize ] && [ ! -d $GOPATH/src/github.com/oxequa/realize ]; then
echo "Realize not found. Downloading it for you..."
go get github.com/oxequa/realize
if [ $? -eq 0 ]; then
echo "Successfully downloaded realize!"
else
echo "Failed downloading realize. Please get it at http://github.com/oxequa/realize"
exit
fi
fi
# ------------------------------------------------------------
# Config file
# ------------------------------------------------------------
# Duplicate the example config file to a real one (which is ignored by git)
if [ ! -f _config/global.json ]; then
echo "Creating _config/global.json"
cp _config/global.example.json _config/global.json
echo "Done."
echo ">>> Please open _config/global.json and update it with your config."
fi
# ------------------------------------------------------------
# Start
# ------------------------------------------------------------
# Start the app
echo "Starting app with realize..."
realize start --run main.go
package main
import (
"fmt"
"log"
"net/http"
"strconv"
"github.com/spf13/viper"
)
func main() {
// Get config from global.json thanks to Viper
appName := viper.GetString("appName")
port := viper.GetInt("server.port")
goPort := ":" + strconv.Itoa(port)
// HTTP
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, you've requested: %s\n", r.URL.Path)
})
fmt.Println("Starting", appName, "on port", goPort)
http.ListenAndServe(goPort, nil)
}
func init() {
InitViper()
}
// Init Viper to use our config located in _config/global.json
func InitViper() {
viper.SetConfigName("global")
viper.AddConfigPath("_config")
err := viper.ReadInConfig()
if err != nil {
log.Fatalf("Fatal error config file: %s \n", err)
}
}
{
"appName": "MyApp",
"server": {
"port": 8080
},
"mongo": {
"host": "localhost",
"dbName": "myDatabase",
"maxWait": 5
},
"oauth": {
"google_client_id": "abcdefghijklmnopqrstuvwxyz.apps.googleusercontent.com",
"google_client_secret": "abcdefghijklmnopqrstuvwxyz"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment