Skip to content

Instantly share code, notes, and snippets.

@liamka
Last active August 29, 2015 14:26
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 liamka/15eec829d516da4cb511 to your computer and use it in GitHub Desktop.
Save liamka/15eec829d516da4cb511 to your computer and use it in GitHub Desktop.
JSON from func make it global
package models
import (
"encoding/json"
"io/ioutil"
)
type Config struct {
Keywords string `json:"keywords"`
Social []struct {
Url string `json:"url"`
Title string `json:"title"`
} `json:"social"`
}
func Conf() Config {
var с Config
configFile, _ := ioutil.ReadFile("config.json")
json.Unmarshal([]byte(configFile), &с)
return с
}
{
"keywords": "keywords1",
"social": [
{"url": "test1", "title": "test1"},
{"url": "test2", "title": "test2"}
],
"mysql": "123123123123"
}
package main
import (
"fmt"
"net/http"
"./models"
)
// Global variables
var config map[string]*models.Config
func indexHandler(w http.ResponseWriter, r *http.Request) {
// Use config
fmt.Println(config["Keywords"]) // Prints nil - why?
}
func main() {
config := models.Conf()
fmt.Println(config.Keywords) // Prints "keywords1"
// Routes
http.HandleFunc("/", indexHandler)
// Get port
http.ListenAndServe(":3000", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment