Hi !
I am new to golang. Actually I need to call json data into html template through members of structure slice. But having problem to send this data with the help of instance (doing something wrong to send properly).The code section is below where is getting problem.
type MyStruct struct {
Name string
Duration string
.....
}
func template1(w http.ResponseWriter, r *http.Request) {
//Send actual data to track instance.(having problem here to send data)
track := MyStruct {
Name:MyStruct.Name,
Duration:MyStruct.Duration,
& other members so on..
}
fp := path.Join("name.html")
tmpl, err := template.ParseFiles(fp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := tmpl.Execute(w, track); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
Actually I have json data which I retrieved through api in my program. As I said I have to make a html template file which could save that certain data part (here MyStruct part) in index file. But I am confused how to send it properly through instance or any other way to do so ?
I have another function having this data like.
func get_content() {
// json data
url := " url name"
res, err := http.Get(url)
//error check here
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err.Error())
}
var data MyStruct
err = json.Unmarshal(body, &data)
if err != nil {
panic(err.Error())
}
fmt.Printf(“Results: %v\n”, data)
Does the get content function need to be called once per incoming request? If so, call it there, store the result in a local variable and pass i to the template. If it just needs to happen once, call it before starting the HTTP server and put the result in a package (top level) variable.
If it’s somewhere in between and it needs to be updated while the HTTP server is running, you will need to add some concurrency handling. This is slightly more complicated, so start with one of the other mechanisms until you’re comfortable with how it works.
Hi Calmh.
I read your comments and tried to fix it but could not. Actually, I have structures and I am getting JSON data through API and unmarshal it in another function and it works perfect. But when I try to write a template function (try to call this data through structure) because I need to display info through html file let’s say I wrote {{.Name}} on a file and have to call this data from defined structure(using localhost on port 8080). When I write like var collect structure_name and write exectue line by giving this parameter it does not show anything on the localhost page. If I try to write separate structue inside the html template function like collect := structure{ Name string and so on}{Name: “Alice”} and use this var in execute line it works to display name, but failed to display json data through structure.
Need guideline!
Thanks in advance.