Skip to content

Instantly share code, notes, and snippets.

@liamka
Created August 28, 2015 13:25
Show Gist options
  • Save liamka/e25ef01d6e8736066769 to your computer and use it in GitHub Desktop.
Save liamka/e25ef01d6e8736066769 to your computer and use it in GitHub Desktop.
main.go
package models
import (
"encoding/json"
"io/ioutil"
)
type Config struct {
Jobs []struct {
Employer string `json:"Employer"`
Role string `json:"Role"`
} `json:"jobs"`
}
func Conf() Config {
var с Config
configFile, _ := ioutil.ReadFile("config.json")
json.Unmarshal([]byte(configFile), &с)
return с
}
{
"jobs": [
{"Employer": "test1", "Role": "test1"}
]
}
package main
import (
"fmt"
"html/template"
"os"
"encoding/json"
"./models"
)
type Person struct {
Name string
Jobs []*Job
}
type Job struct {
Employer string
Role string
}
var (
config models.Config
)
const templ = `The name is {{.Name}}.
{{with .Jobs}}
{{range .}}
An employer is {{.Employer}}
and the role is {{.Role}}
{{end}}
{{end}}
`
func main() {
job1 := Job{Employer: "Monash", Role: "Honorary"}
job2 := Job{Employer: "Box Hill", Role: "Head of HE"}
// HERE!!!!!!!!!
byt := []byte(config)
var dat Person
if err := json.Unmarshal(byt, &dat); err != nil {
panic(err)
}
person := Person{
Name: "jan",
Jobs: []*Job{&job1, &job2},
}
person.Jobs = append(person.Jobs, dat.Jobs...)
t := template.New("Person template")
t, err := t.Parse(templ)
checkError(err)
err = t.Execute(os.Stdout, person)
checkError(err)
}
func checkError(err error) {
if err != nil {
fmt.Println("Fatal error ", err.Error())
os.Exit(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment