Answer the question
In order to leave comments, you need to log in
Why is it throwing a 500 go error?
I rewrote the functions and gives a 500 error now because of it, but the reason is not indicated:
func searchHandler(w http.ResponseWriter, r *http.Request) {
u, err := url.Parse(r.URL.String())
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal server error"))
return
}
params := u.Query()
searchKey := params.Get("q")
page := params.Get("page")
if page == "" {
page = "1"
}
search := &Search{}
search.SearchKey = searchKey
next, err := strconv.Atoi(page)
if err != nil {
http.Error(w, "Unexpected server error", http.StatusInternalServerError)
return
}
search.NextPage = next
pageSize := 20
endpoint := fmt.Sprintf("https://newsapi.org/v2/everything?q=%s&pageSize=%d&page=%d&apiKey=%s&sortBy=publishedAt&language=en", url.QueryEscape(search.SearchKey), pageSize, search.NextPage, *apiKey)
resp, err := http.Get(endpoint)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
w.WriteHeader(http.StatusInternalServerError)
return
}
err = json.NewDecoder(resp.Body).Decode(&search.Results)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
search.TotalPages = int(math.Ceil(float64(search.Results.TotalResults / pageSize)))
err = tpl.Execute(w, search)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
}
Answer the question
In order to leave comments, you need to log in
You check for an error everywhere, but do not display the error itself.
You can, for example, like this:
http.Error(w, err.Error(), http.StatusInternalServerError)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question