Skip to content

Instantly share code, notes, and snippets.

@liamka
Last active August 29, 2015 14:26
Show Gist options
  • Select an option

  • Save liamka/15eec829d516da4cb511 to your computer and use it in GitHub Desktop.

Select an option

Save liamka/15eec829d516da4cb511 to your computer and use it in GitHub Desktop.

Revisions

  1. liamka revised this gist Jul 30, 2015. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion main.go
    Original file line number Diff line number Diff line change
    @@ -11,7 +11,7 @@ var config map[string]*models.Config

    func indexHandler(w http.ResponseWriter, r *http.Request) {
    // Use config
    fmt.Println(config["Keywords"]) // nil
    fmt.Println(config["Keywords"]) // Prints nil - why?
    }

    func main() {
  2. liamka created this gist Jul 30, 2015.
    21 changes: 21 additions & 0 deletions Config.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    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 с
    }
    8 changes: 8 additions & 0 deletions config.json
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,8 @@
    {
    "keywords": "keywords1",
    "social": [
    {"url": "test1", "title": "test1"},
    {"url": "test2", "title": "test2"}
    ],
    "mysql": "123123123123"
    }
    26 changes: 26 additions & 0 deletions main.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    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"]) // nil
    }

    func main() {
    config := models.Conf()
    fmt.Println(config.Keywords) // Prints "keywords1"

    // Routes
    http.HandleFunc("/", indexHandler)

    // Get port
    http.ListenAndServe(":3000", nil)
    }