I was making an api request on page load of a specific html template. This is causing problems so I would like to make the api call when the program runs so the data is accessible when the html page is viewed.
So I am new to GoLang and am having trouble understanding what arguments to pass to this function when I call it in main.
func RequestTopMovies(w http.ResponseWriter, r *http.Request) {
res, err := http.Get(url)
if err != nil {
panic(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err)
}
var p Payload
err = json.Unmarshal(body, &p)
if err != nil {
panic(err)
}
for i := 0; i < len(p.Results); i++ {
fmt.Println(p.Results[i].Overview) // Prints to your terminal
}
}
So now at this point I have the response in p.Results.
I want to be able to access this data in other places in my program. I was thinking I could just call the function.
So how can I call this function in main?
func main() {
RequestTopMovies(http.ResponseWriter, http.Request)
http.HandleFunc("/", mainHandler)
http.HandleFunc("/about", aboutHandler)
http.HandleFunc("/TopPicks", TopMoviesHandler)
http.ListenAndServe(":8080", nil)
}
How can I pass this function to another function to have it return the response as well?