I try to store the menu in a database and fill a Go html template with this. I have managed to fetch the JSON and the filling of Go html template. Independent of each other. But how do I transfer the JSON from the func main into the template func page?
package main
import (
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"os"
)
func main() {
resp, err := http.Get("https://api3.go4webdev.org/menu/all")
if err != nil {
fmt.Println("No response")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Println(string(body)) // how pass this to "func page" and populate the menu?
page()
}
func page() {
fmt.Println()
t := template.Must(template.New("").Parse(templ))
m := map[string]interface{}{}
if err := json.Unmarshal([]byte(jsondata), &m); err != nil {
panic(err)
}
if err := t.Execute(os.Stdout, m); err != nil {
panic(err)
}
}
const templ = `
<html><body>
<ul>
<li id={{.menu_id}}>{{.menu_txt}}</li>
<li id={{.menu_id}}>{{.menu_txt}}</li>
</ul>
</body></html>`
const jsondata = `{"menu_id":"1", "menu_txt": "Home"}`
You can unmarshal a JSON array into a Go []interface, or you can unmarshal a JSON object into a Go map[string]interface{}. Better would be to use more specific Go types that match the schema of your JSON.
The error messages says what the problem is. You are trying to unmarshal a json array into a map. I told you and showed you that you can unmarshal a json array into a slice. If your json is an object, then you can unmarshal it into a map. You need to have some understanding of the structure of the json.
m := []map[string]interface{} assigns the a type to the variable m because the right-hand side is a type of a slice of maps, not a value. var m []map[string]interface{} declares the variable m to be of a type (of slice of maps). It is implicitly initialized to the zero-value of the type. := is a shorthand to declare a variable and initialize it. The variable’s value will be set to the value of the right-hand side, and it’s type will be inferred from the type of the right-hand side. A Tour of Go
When using json.Unmarshal, it is unnecessary to initialize the variable because Unmarshal will set the variable`s value.