refactor: replace logrus with log/slog

This commit is contained in:
rramiachraf 2024-05-02 21:29:50 +01:00
parent 56c745d6f5
commit c940b4a2cd
18 changed files with 120 additions and 70 deletions

View File

@ -6,7 +6,6 @@ import (
"strings"
"github.com/PuerkitoBio/goquery"
"github.com/sirupsen/logrus"
)
type Song struct {
@ -49,17 +48,25 @@ type customPerformance struct {
}
}
func (s *Song) parseLyrics(doc *goquery.Document) {
func (s *Song) parseLyrics(doc *goquery.Document) error {
var htmlError error
doc.Find("[data-lyrics-container='true']").Each(func(i int, ss *goquery.Selection) {
h, err := ss.Html()
if err != nil {
logrus.Errorln("unable to parse lyrics", err)
htmlError = err
}
s.Lyrics += h
})
if htmlError != nil {
return htmlError
}
return nil
}
func (s *Song) parseSongData(doc *goquery.Document) {
func (s *Song) parseSongData(doc *goquery.Document) error {
attr, exists := doc.Find("meta[property='twitter:app:url:iphone']").Attr("content")
if exists {
songID := strings.Replace(attr, "genius://songs/", "", 1)
@ -68,7 +75,7 @@ func (s *Song) parseSongData(doc *goquery.Document) {
res, err := sendRequest(u)
if err != nil {
logrus.Errorln(err)
return err
}
defer res.Body.Close()
@ -77,7 +84,7 @@ func (s *Song) parseSongData(doc *goquery.Document) {
decoder := json.NewDecoder(res.Body)
err = decoder.Decode(&data)
if err != nil {
logrus.Errorln(err)
return err
}
songData := data.Response.Song
@ -99,6 +106,8 @@ func (s *Song) parseSongData(doc *goquery.Document) {
s.Credits[perf.Label] = strings.Join(artists, ", ")
}
}
return nil
}
func truncateText(text string) string {
@ -111,7 +120,14 @@ func truncateText(text string) string {
return text
}
func (s *Song) Parse(doc *goquery.Document) {
s.parseLyrics(doc)
s.parseSongData(doc)
func (s *Song) Parse(doc *goquery.Document) error {
if err := s.parseLyrics(doc); err != nil {
return err
}
if err := s.parseSongData(doc); err != nil {
return err
}
return nil
}

1
go.mod
View File

@ -11,7 +11,6 @@ require (
github.com/caffix/cloudflare-roundtripper v0.0.0-20181218223503-4c29d231c9cb
github.com/gorilla/handlers v1.5.2
github.com/gorilla/mux v1.8.1
github.com/sirupsen/logrus v1.9.3
)
require (

4
go.sum
View File

@ -196,15 +196,12 @@ github.com/shurcooL/reactions v0.0.0-20181006231557-f2e0b4ca5b82/go.mod h1:TCR1l
github.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/shurcooL/users v0.0.0-20180125191416-49c67e49c537/go.mod h1:QJTqeLYEDaXHZDBsXlPCDqdhQuJkuw4NOtaxYe3xii4=
github.com/shurcooL/webdavfs v0.0.0-20170829043945-18c3829fa133/go.mod h1:hKmq5kWdCj2z2KEozexVbfEZIWiTjhE0+UjmZgPqehw=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/sourcegraph/annotate v0.0.0-20160123013949-f4cad6c6324d/go.mod h1:UdhH50NIW0fCiwBSr0co2m7BnFLdv4fQTgdqdJTHFeE=
github.com/sourcegraph/syntaxhighlight v0.0.0-20170531221838-bd320f5d308e/go.mod h1:HuIsMU8RRBOtsCgI77wP899iHVBQpCmg4ErYMZB+2IA=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA=
@ -312,7 +309,6 @@ golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220422013727-9388b58f7150/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=

View File

@ -8,11 +8,11 @@ import (
"github.com/PuerkitoBio/goquery"
"github.com/gorilla/mux"
"github.com/rramiachraf/dumb/data"
"github.com/rramiachraf/dumb/utils"
"github.com/rramiachraf/dumb/views"
"github.com/sirupsen/logrus"
)
func album(l *logrus.Logger) http.HandlerFunc {
func album(l *utils.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
artist := mux.Vars(r)["artist"]
albumName := mux.Vars(r)["albumName"]
@ -28,7 +28,7 @@ func album(l *logrus.Logger) http.HandlerFunc {
resp, err := sendRequest(url)
if err != nil {
l.Errorln(err)
l.Error(err.Error())
w.WriteHeader(http.StatusInternalServerError)
views.ErrorPage(500, "cannot reach Genius servers").Render(context.Background(), w)
return
@ -44,7 +44,7 @@ func album(l *logrus.Logger) http.HandlerFunc {
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
l.Errorln(err)
l.Error(err.Error())
w.WriteHeader(http.StatusInternalServerError)
views.ErrorPage(500, "something went wrong").Render(context.Background(), w)
return
@ -52,20 +52,20 @@ func album(l *logrus.Logger) http.HandlerFunc {
cf := doc.Find(".cloudflare_content").Length()
if cf > 0 {
l.Errorln("cloudflare got in the way")
l.Error("cloudflare got in the way")
views.ErrorPage(500, "i'll fix this later #21").Render(context.Background(), w)
return
}
var a data.Album
if err = a.Parse(doc); err != nil {
l.Error(err)
l.Error(err.Error())
}
views.AlbumPage(a).Render(context.Background(), w)
if err = setCache(id, a); err != nil {
l.Errorln(err)
l.Error(err.Error())
}
}
}

View File

@ -3,10 +3,12 @@ package handlers
import (
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/PuerkitoBio/goquery"
"github.com/sirupsen/logrus"
"github.com/rramiachraf/dumb/utils"
)
func TestAlbum(t *testing.T) {
@ -19,7 +21,7 @@ func TestAlbum(t *testing.T) {
}
rr := httptest.NewRecorder()
l := logrus.New()
l := utils.NewLogger(os.Stdout)
m := New(l)
m.ServeHTTP(rr, r)

View File

@ -12,11 +12,11 @@ import (
"github.com/PuerkitoBio/goquery"
"github.com/gorilla/mux"
"github.com/rramiachraf/dumb/data"
"github.com/rramiachraf/dumb/utils"
"github.com/rramiachraf/dumb/views"
"github.com/sirupsen/logrus"
)
func annotations(l *logrus.Logger) http.HandlerFunc {
func annotations(l *utils.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["annotation-id"]
if a, err := getCache[data.Annotation]("annotation:" + id); err == nil {
@ -24,7 +24,7 @@ func annotations(l *logrus.Logger) http.HandlerFunc {
w.Header().Set("content-type", "application/json")
if err = encoder.Encode(&a); err != nil {
l.Errorln(err)
l.Error(err.Error())
}
return
@ -34,7 +34,7 @@ func annotations(l *logrus.Logger) http.HandlerFunc {
resp, err := sendRequest(url)
if err != nil {
l.Errorln(err)
l.Error(err.Error())
w.WriteHeader(http.StatusInternalServerError)
views.ErrorPage(500, "cannot reach genius servers").Render(context.Background(), w)
return
@ -51,7 +51,7 @@ func annotations(l *logrus.Logger) http.HandlerFunc {
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(resp.Body)
if err != nil {
l.Errorln("Error paring genius api response", err)
l.Error("Error paring genius api response: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
views.ErrorPage(500, "something went wrong").Render(context.Background(), w)
return
@ -60,7 +60,7 @@ func annotations(l *logrus.Logger) http.HandlerFunc {
var data data.AnnotationsResponse
err = json.Unmarshal(buf.Bytes(), &data)
if err != nil {
l.Errorf("could not unmarshal json: %s\n", err)
l.Error("could not unmarshal json: %s\n", err)
w.WriteHeader(http.StatusInternalServerError)
views.ErrorPage(500, "something went wrong").Render(context.Background(), w)
return
@ -73,12 +73,12 @@ func annotations(l *logrus.Logger) http.HandlerFunc {
encoder := json.NewEncoder(w)
if err = encoder.Encode(&body); err != nil {
l.Errorln("Error sending response: ", err)
l.Error("Error sending response: %s", err.Error())
return
}
if err = setCache("annotation:"+id, body); err != nil {
l.Errorln(err)
l.Error(err.Error())
}
}
}

View File

@ -4,9 +4,10 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/sirupsen/logrus"
"github.com/rramiachraf/dumb/utils"
)
func TestAnnotations(t *testing.T) {
@ -18,7 +19,7 @@ func TestAnnotations(t *testing.T) {
}
rr := httptest.NewRecorder()
l := logrus.New()
l := utils.NewLogger(os.Stdout)
m := New(l)
m.ServeHTTP(rr, r)

View File

@ -7,11 +7,11 @@ import (
"github.com/a-h/templ"
gorillaHandlers "github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/rramiachraf/dumb/utils"
"github.com/rramiachraf/dumb/views"
"github.com/sirupsen/logrus"
)
func New(logger *logrus.Logger) *mux.Router {
func New(logger *utils.Logger) *mux.Router {
r := mux.NewRouter()
r.Use(mustHeaders)

View File

@ -5,22 +5,22 @@ import (
"io"
"net/http"
"github.com/rramiachraf/dumb/utils"
"github.com/rramiachraf/dumb/views"
"github.com/sirupsen/logrus"
)
const ContentTypeJSON = "application/json"
// TODO: move this to utils, so it can be used by other handlers.
func sendError(err error, status int, msg string, l *logrus.Logger, w http.ResponseWriter) {
l.Errorln(err)
func sendError(err error, status int, msg string, l *utils.Logger, w http.ResponseWriter) {
l.Error(err.Error())
w.WriteHeader(status)
if err := views.ErrorPage(status, msg).Render(context.Background(), w); err != nil {
l.Errorln(err)
l.Error(err.Error())
}
}
func instances(l *logrus.Logger) http.HandlerFunc {
func instances(l *utils.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if instances, err := getCache[[]byte]("instances"); err == nil {
w.Header().Set("content-type", ContentTypeJSON)
@ -46,11 +46,11 @@ func instances(l *logrus.Logger) http.HandlerFunc {
w.Header().Set("content-type", ContentTypeJSON)
if _, err = w.Write(instances); err != nil {
l.Errorln(err)
l.Error(err.Error())
}
if err = setCache("instances", instances); err != nil {
l.Errorln(err)
l.Error(err.Error())
}
}
}

View File

@ -4,9 +4,10 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/sirupsen/logrus"
"github.com/rramiachraf/dumb/utils"
)
func TestInstancesList(t *testing.T) {
@ -16,7 +17,7 @@ func TestInstancesList(t *testing.T) {
}
rr := httptest.NewRecorder()
l := logrus.New()
l := utils.NewLogger(os.Stdout)
m := New(l)
m.ServeHTTP(rr, r)

View File

@ -8,11 +8,11 @@ import (
"github.com/PuerkitoBio/goquery"
"github.com/gorilla/mux"
"github.com/rramiachraf/dumb/data"
"github.com/rramiachraf/dumb/utils"
"github.com/rramiachraf/dumb/views"
"github.com/sirupsen/logrus"
)
func lyrics(l *logrus.Logger) http.HandlerFunc {
func lyrics(l *utils.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// prefer artist-song over annotation-id for cache key when available
id := mux.Vars(r)["artist-song"]
@ -30,7 +30,7 @@ func lyrics(l *logrus.Logger) http.HandlerFunc {
url := fmt.Sprintf("https://genius.com/%s", id)
resp, err := sendRequest(url)
if err != nil {
l.Errorln(err)
l.Error(err.Error())
w.WriteHeader(http.StatusInternalServerError)
views.ErrorPage(500, "cannot reach Genius servers").Render(context.Background(), w)
return
@ -46,7 +46,7 @@ func lyrics(l *logrus.Logger) http.HandlerFunc {
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
l.Errorln(err)
l.Error(err.Error())
w.WriteHeader(http.StatusInternalServerError)
views.ErrorPage(500, "something went wrong").Render(context.Background(), w)
return
@ -54,17 +54,19 @@ func lyrics(l *logrus.Logger) http.HandlerFunc {
cf := doc.Find(".cloudflare_content").Length()
if cf > 0 {
l.Errorln("cloudflare got in the way")
l.Error("cloudflare got in the way")
views.ErrorPage(500, "TODO: fix Cloudflare #21").Render(context.Background(), w)
return
}
var s data.Song
s.Parse(doc)
if err := s.Parse(doc); err != nil {
l.Error(err.Error())
}
views.LyricsPage(s).Render(context.Background(), w)
if err = setCache(id, s); err != nil {
l.Errorln(err)
l.Error(err.Error())
}
}
}

View File

@ -3,10 +3,11 @@ package handlers
import (
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/PuerkitoBio/goquery"
"github.com/sirupsen/logrus"
"github.com/rramiachraf/dumb/utils"
)
func TestLyrics(t *testing.T) {
@ -31,7 +32,7 @@ func testLyrics(t *testing.T, url string) {
}
rr := httptest.NewRecorder()
l := logrus.New()
l := utils.NewLogger(os.Stdout)
m := New(l)
m.ServeHTTP(rr, r)

View File

@ -9,8 +9,8 @@ import (
"strings"
"github.com/gorilla/mux"
"github.com/rramiachraf/dumb/utils"
"github.com/rramiachraf/dumb/views"
"github.com/sirupsen/logrus"
)
func isValidExt(ext string) bool {
@ -24,7 +24,7 @@ func isValidExt(ext string) bool {
return false
}
func imageProxy(l *logrus.Logger) http.HandlerFunc {
func imageProxy(l *utils.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
v := mux.Vars(r)
f := v["filename"]
@ -41,7 +41,7 @@ func imageProxy(l *logrus.Logger) http.HandlerFunc {
res, err := sendRequest(url)
if err != nil {
l.Errorln(err)
l.Error(err.Error())
w.WriteHeader(http.StatusInternalServerError)
views.ErrorPage(500, "cannot reach Genius servers").Render(context.Background(), w)
return
@ -56,7 +56,7 @@ func imageProxy(l *logrus.Logger) http.HandlerFunc {
w.Header().Add("Content-type", mime.TypeByExtension("."+ext))
w.Header().Add("Cache-Control", "max-age=1296000")
if _, err = io.Copy(w, res.Body); err != nil {
l.Errorln("unable to write image", err)
l.Error("unable to write image, %s", err.Error())
}
}
}

View File

@ -4,9 +4,10 @@ import (
"mime"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/sirupsen/logrus"
"github.com/rramiachraf/dumb/utils"
)
func TestImageProxy(t *testing.T) {
@ -18,7 +19,7 @@ func TestImageProxy(t *testing.T) {
}
rr := httptest.NewRecorder()
l := logrus.New()
l := utils.NewLogger(os.Stdout)
m := New(l)
m.ServeHTTP(rr, r)

View File

@ -8,18 +8,18 @@ import (
"net/url"
"github.com/rramiachraf/dumb/data"
"github.com/rramiachraf/dumb/utils"
"github.com/rramiachraf/dumb/views"
"github.com/sirupsen/logrus"
)
func search(l *logrus.Logger) http.HandlerFunc {
func search(l *utils.Logger) http.HandlerFunc {
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))
res, err := sendRequest(url)
if err != nil {
l.Errorln(err)
l.Error(err.Error())
w.WriteHeader(http.StatusInternalServerError)
views.ErrorPage(500, "cannot reach Genius servers").Render(context.Background(), w)
return
@ -31,7 +31,7 @@ func search(l *logrus.Logger) http.HandlerFunc {
d := json.NewDecoder(res.Body)
if err = d.Decode(&sRes); err != nil {
l.Errorln(err)
l.Error(err.Error())
w.WriteHeader(http.StatusInternalServerError)
views.ErrorPage(500, "something went wrong").Render(context.Background(), w)
}

View File

@ -3,10 +3,11 @@ package handlers
import (
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/PuerkitoBio/goquery"
"github.com/sirupsen/logrus"
"github.com/rramiachraf/dumb/utils"
)
func TestSearch(t *testing.T) {
@ -19,7 +20,7 @@ func TestSearch(t *testing.T) {
}
rr := httptest.NewRecorder()
l := logrus.New()
l := utils.NewLogger(os.Stdout)
m := New(l)
m.ServeHTTP(rr, r)

14
main.go
View File

@ -9,11 +9,11 @@ import (
"time"
"github.com/rramiachraf/dumb/handlers"
"github.com/sirupsen/logrus"
"github.com/rramiachraf/dumb/utils"
)
func main() {
var logger = logrus.New()
logger := utils.NewLogger(os.Stdout)
server := &http.Server{
Handler: handlers.New(logger),
@ -25,14 +25,18 @@ func main() {
if port == 0 {
port = 5555
logger.Info("using default port %d", port)
}
l, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
logger.Fatalln(err)
logger.Error(err.Error())
}
logger.Infof("server is listening on port %d\n", port)
logger.Info("server is listening on port %d", port)
logger.Fatalln(server.Serve(l))
if err := server.Serve(l); err != nil {
logger.Error(err.Error())
os.Exit(1)
}
}

26
utils/logger.go Normal file
View File

@ -0,0 +1,26 @@
package utils
import (
"fmt"
"io"
"log/slog"
)
type Logger struct {
slog *slog.Logger
}
func NewLogger(w io.WriteCloser) *Logger {
handler := slog.NewTextHandler(w, &slog.HandlerOptions{})
sl := slog.New(handler)
return &Logger{slog: sl}
}
func (l *Logger) Error(f string, args ...any) {
l.slog.Error(fmt.Sprintf(f, args...))
}
func (l *Logger) Info(f string, args ...any) {
l.slog.Info(fmt.Sprintf(f, args...))
}