dumb/handlers/annotations.go

81 lines
2.1 KiB
Go
Raw Permalink Normal View History

package handlers
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/rramiachraf/dumb/data"
2024-05-02 21:29:50 +01:00
"github.com/rramiachraf/dumb/utils"
"github.com/rramiachraf/dumb/views"
)
2024-05-02 21:29:50 +01:00
func annotations(l *utils.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
2024-04-06 00:14:51 -06:00
id := mux.Vars(r)["annotation-id"]
2024-03-04 20:43:46 +01:00
if a, err := getCache[data.Annotation]("annotation:" + id); err == nil {
2024-03-04 19:49:03 +01:00
encoder := json.NewEncoder(w)
w.Header().Set("content-type", "application/json")
2024-03-04 20:43:46 +01:00
if err = encoder.Encode(&a); err != nil {
2024-05-02 21:29:50 +01:00
l.Error(err.Error())
}
2024-03-04 20:43:46 +01:00
return
}
url := fmt.Sprintf("https://genius.com/api/referents/%s?text_format=html", id)
resp, err := utils.SendRequest(url)
if err != nil {
2024-05-02 21:29:50 +01:00
l.Error(err.Error())
w.WriteHeader(http.StatusInternalServerError)
2024-07-14 00:43:06 +01:00
utils.RenderTemplate(w, views.ErrorPage(500, "cannot reach genius servers"), l)
return
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
w.WriteHeader(http.StatusNotFound)
2024-07-14 00:43:06 +01:00
utils.RenderTemplate(w, views.ErrorPage(404, "page not found"), l)
return
}
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(resp.Body)
if err != nil {
2024-05-02 21:29:50 +01:00
l.Error("Error paring genius api response: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
2024-07-14 00:43:06 +01:00
utils.RenderTemplate(w, views.ErrorPage(500, "something went wrong"), l)
return
}
var data data.AnnotationsResponse
err = json.Unmarshal(buf.Bytes(), &data)
if err != nil {
2024-05-02 21:29:50 +01:00
l.Error("could not unmarshal json: %s\n", err)
w.WriteHeader(http.StatusInternalServerError)
2024-07-14 00:43:06 +01:00
utils.RenderTemplate(w, views.ErrorPage(500, "something went wrong"), l)
return
}
annotation := data.Response.Referent.Annotations[0]
annotation.Body.HTML = utils.CleanBody(annotation.Body.HTML)
2024-03-04 20:43:46 +01:00
w.Header().Set("content-type", "application/json")
encoder := json.NewEncoder(w)
if err = encoder.Encode(&annotation); err != nil {
2024-05-02 21:29:50 +01:00
l.Error("Error sending response: %s", err.Error())
return
}
if err = setCache("annotation:"+id, annotation); err != nil {
2024-05-02 21:29:50 +01:00
l.Error(err.Error())
2024-03-04 18:46:23 +01:00
}
}
}