I wrote an app that makes a request to an API and gets a JSON response. When I run the app it displays the json in the terminal.
go run main.go
I want to make this run in the browser and I found this, which allowed me to print a string to the browser.
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "This is a string")
}
Then in main
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
Now that I have a string being printed to the screen and I have a json response coming from the api I am using, how can I add the json response to the browser instead of the string?
Would it be best to put the response into a string then just bring it to the browser?
Currently I am printing the json response to the terminal like this,
type Payload struct {
Page int
Results []Data
}
type Data struct {
PosterPath string `json:"poster_path"`
Adult bool `json:"adult"`
Overview string `json:"overview"`
ReleaseDate string `json:"release_date"`
GenreIds []int `json:"genre_ids"`
Id int `json:"id"`
OriginalTitle string `json:"original_title"`
OriginalLanguage string `json:"original_language"`
Title string `json:"title"`
BackdropPath string `json:"backdrop_path"`
Popularity float64 `json:"popularity"`
VoteCount int `json:"vote_count"`
Video bool `json:"video"`
VoteAverage float64 `json:"vote_average"`
}
Then inside main()
I do this,
for i := 0; i < len(p.Results); i++ {
fmt.Println(
ImgUrl+p.Results[i].PosterPath, "
", p.Results[i].Adult,
p.Results[i].Overview, "
", p.Results[i].ReleaseDate,
p.Results[i].GenreIds, "
", p.Results[i].Id,
p.Results[i].OriginalTitle, "
", p.Results[i].OriginalLanguage,
p.Results[i].Title, "
", ImgUrl+p.Results[i].BackdropPath,
p.Results[i].Popularity, "
", p.Results[i].VoteCount,
p.Results[i].Video, "
", p.Results[i].VoteAverage,
)
What would be the Go way to do this for building web applications? My end goal here is to take user input and recreate my api call based on the information they provide.