2024-03-04 14:59:47 +01:00
|
|
|
package handlers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
2024-09-27 13:18:58 +01:00
|
|
|
"strings"
|
2024-03-04 14:59:47 +01:00
|
|
|
|
|
|
|
"github.com/rramiachraf/dumb/data"
|
2024-05-02 21:29:50 +01:00
|
|
|
"github.com/rramiachraf/dumb/utils"
|
2024-03-04 14:59:47 +01:00
|
|
|
"github.com/rramiachraf/dumb/views"
|
|
|
|
)
|
|
|
|
|
2024-05-02 21:29:50 +01:00
|
|
|
func search(l *utils.Logger) http.HandlerFunc {
|
2024-03-04 14:59:47 +01:00
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
query := r.URL.Query().Get("q")
|
|
|
|
url := fmt.Sprintf(`https://genius.com/api/search/multi?q=%s`, url.QueryEscape(query))
|
|
|
|
|
2024-05-03 12:45:58 +01:00
|
|
|
res, err := utils.SendRequest(url)
|
2024-03-04 14:59:47 +01:00
|
|
|
if err != nil {
|
2024-05-02 21:29:50 +01:00
|
|
|
l.Error(err.Error())
|
2024-03-04 14:59:47 +01:00
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
2024-09-27 13:18:58 +01:00
|
|
|
utils.RenderTemplate(w, views.ErrorPage(500, "cannot reach Genius servers."), l)
|
2024-03-04 14:59:47 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
defer res.Body.Close()
|
|
|
|
|
2024-09-27 13:18:58 +01:00
|
|
|
if strings.HasPrefix(res.Header.Get("content-type"), "text/html") {
|
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
utils.RenderTemplate(w, views.ErrorPage(500, "Cloudflare got in the way."), l)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-03-04 14:59:47 +01:00
|
|
|
var sRes data.SearchResponse
|
|
|
|
|
|
|
|
d := json.NewDecoder(res.Body)
|
2024-03-04 18:46:23 +01:00
|
|
|
if err = d.Decode(&sRes); err != nil {
|
2024-05-02 21:29:50 +01:00
|
|
|
l.Error(err.Error())
|
2024-03-04 18:46:23 +01:00
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
2024-09-27 13:18:58 +01:00
|
|
|
utils.RenderTemplate(w, views.ErrorPage(500, "something went wrong."), l)
|
|
|
|
return
|
2024-03-04 18:46:23 +01:00
|
|
|
}
|
2024-03-04 14:59:47 +01:00
|
|
|
|
|
|
|
results := data.SearchResults{Query: query, Sections: sRes.Response.Sections}
|
|
|
|
|
2024-07-14 00:43:06 +01:00
|
|
|
utils.RenderTemplate(w, views.SearchPage(results), l)
|
2024-03-04 14:59:47 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|