Skip to content

Commit

Permalink
feat: switch from chi to built in net/http
Browse files Browse the repository at this point in the history
Signed-off-by: Matt Gleich <[email protected]>
  • Loading branch information
gleich committed Jan 8, 2025
1 parent 0257dba commit 59d024b
Show file tree
Hide file tree
Showing 10 changed files with 38 additions and 47 deletions.
18 changes: 7 additions & 11 deletions cmd/lcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import (
"time"

"github.com/gleich/lumber/v3"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"pkg.mattglei.ch/lcp-v2/internal/apis/applemusic"
"pkg.mattglei.ch/lcp-v2/internal/apis/github"
"pkg.mattglei.ch/lcp-v2/internal/apis/steam"
Expand All @@ -20,18 +18,16 @@ func main() {

secrets.Load()

r := chi.NewRouter()
r.Use(middleware.Recoverer)
r.Use(middleware.RedirectSlashes)
r.HandleFunc("/", rootRedirect)
mux := http.NewServeMux()
mux.HandleFunc("/", rootRedirect)

github.Setup(r)
strava.Setup(r)
steam.Setup(r)
applemusic.Setup(r)
github.Setup(mux)
strava.Setup(mux)
steam.Setup(mux)
applemusic.Setup(mux)

lumber.Info("starting server")
err := http.ListenAndServe(":8000", r)
err := http.ListenAndServe(":8000", mux)
if err != nil {
lumber.Fatal(err, "failed to start router")
}
Expand Down
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ require (
github.com/buckket/go-blurhash v1.1.0
github.com/caarlos0/env/v11 v11.3.1
github.com/gleich/lumber/v3 v3.0.2
github.com/go-chi/chi/v5 v5.2.0
github.com/joho/godotenv v1.5.1
github.com/minio/minio-go/v7 v7.0.82
github.com/shurcooL/githubv4 v0.0.0-20240727222349-48295856cce7
Expand Down
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/gleich/lumber/v3 v3.0.2 h1:wq8+yTb2NEbT7XEA17mSQ7U2LPJRVNBZWQ6590xzf5k=
github.com/gleich/lumber/v3 v3.0.2/go.mod h1:ZLoHXBIBFNLa58nkJnqhVjPFRqwGctEZyiEDv2wvX8c=
github.com/go-chi/chi/v5 v5.2.0 h1:Aj1EtB0qR2Rdo2dG4O94RIU35w2lvQSj6BRA4+qwFL0=
github.com/go-chi/chi/v5 v5.2.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
github.com/goccy/go-json v0.10.4 h1:JSwxQzIqKfmFX1swYPpUThQZp/Ka4wzJdK0LWVytLPM=
Expand Down
8 changes: 4 additions & 4 deletions internal/apis/applemusic/applemusic.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"time"

"github.com/gleich/lumber/v3"
"github.com/go-chi/chi/v5"
"pkg.mattglei.ch/lcp-v2/internal/auth"
"pkg.mattglei.ch/lcp-v2/internal/cache"
)
Expand Down Expand Up @@ -59,15 +58,15 @@ func cacheUpdate() (cacheData, error) {
}, nil
}

func Setup(router *chi.Mux) {
func Setup(mux *http.ServeMux) {
data, err := cacheUpdate()
if err != nil {
lumber.Fatal(err, "initial fetch of cache data failed")
}

applemusicCache := cache.New("applemusic", data)
router.Get("/applemusic", serveHTTP(applemusicCache))
router.Get("/applemusic/playlists/{id}", playlistEndpoint(applemusicCache))
mux.HandleFunc("GET /applemusic", serveHTTP(applemusicCache))
mux.HandleFunc("GET /applemusic/playlists/{id}", playlistEndpoint(applemusicCache))
go applemusicCache.UpdatePeriodically(cacheUpdate, 30*time.Second)
lumber.Done("setup apple music cache")
}
Expand All @@ -82,6 +81,7 @@ func serveHTTP(c *cache.Cache[cacheData]) http.HandlerFunc {
if !auth.IsAuthorized(w, r) {
return
}

w.Header().Set("Content-Type", "application/json")
c.DataMutex.RLock()

Expand Down
3 changes: 1 addition & 2 deletions internal/apis/applemusic/playlists.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"time"

"github.com/gleich/lumber/v3"
"github.com/go-chi/chi/v5"
"pkg.mattglei.ch/lcp-v2/internal/apis"
"pkg.mattglei.ch/lcp-v2/internal/auth"
"pkg.mattglei.ch/lcp-v2/internal/cache"
Expand Down Expand Up @@ -99,7 +98,7 @@ func playlistEndpoint(c *cache.Cache[cacheData]) http.HandlerFunc {
if !auth.IsAuthorized(w, r) {
return
}
id := chi.URLParam(r, "id")
id := r.PathValue("id")

c.DataMutex.RLock()
var p *playlist
Expand Down
6 changes: 3 additions & 3 deletions internal/apis/github/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ package github

import (
"context"
"net/http"
"time"

"github.com/gleich/lumber/v3"
"github.com/go-chi/chi/v5"
"github.com/shurcooL/githubv4"
"golang.org/x/oauth2"
"pkg.mattglei.ch/lcp-v2/internal/cache"
"pkg.mattglei.ch/lcp-v2/internal/secrets"
)

func Setup(router *chi.Mux) {
func Setup(mux *http.ServeMux) {
githubTokenSource := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: secrets.SECRETS.GitHubAccessToken},
)
Expand All @@ -25,7 +25,7 @@ func Setup(router *chi.Mux) {
}

githubCache := cache.New("github", pinnedRepos)
router.Get("/github", githubCache.ServeHTTP())
mux.HandleFunc("GET /github", githubCache.ServeHTTP)
go githubCache.UpdatePeriodically(
func() ([]repository, error) { return fetchPinnedRepos(githubClient) },
1*time.Minute,
Expand Down
6 changes: 3 additions & 3 deletions internal/apis/steam/steam.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
package steam

import (
"net/http"
"time"

"github.com/gleich/lumber/v3"
"github.com/go-chi/chi/v5"
"pkg.mattglei.ch/lcp-v2/internal/cache"
)

func Setup(router *chi.Mux) {
func Setup(mux *http.ServeMux) {
games, err := fetchRecentlyPlayedGames()
if err != nil {
lumber.Fatal(err, "initial fetch of games failed")
}

steamCache := cache.New("steam", games)
router.Get("/steam", steamCache.ServeHTTP())
mux.HandleFunc("GET /steam", steamCache.ServeHTTP)
go steamCache.UpdatePeriodically(fetchRecentlyPlayedGames, 5*time.Minute)
lumber.Done("setup steam cache")
}
2 changes: 1 addition & 1 deletion internal/apis/strava/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,12 @@ func eventRoute(
tokens tokens,
) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
if err != nil {
lumber.Error(err, "reading response body failed")
return
}
defer r.Body.Close()

var eventData event
err = json.Unmarshal(body, &eventData)
Expand Down
11 changes: 6 additions & 5 deletions internal/apis/strava/strava.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
package strava

import (
"net/http"

"github.com/gleich/lumber/v3"
"github.com/go-chi/chi/v5"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"pkg.mattglei.ch/lcp-v2/internal/cache"
"pkg.mattglei.ch/lcp-v2/internal/secrets"
)

func Setup(router *chi.Mux) {
func Setup(mux *http.ServeMux) {
stravaTokens := loadTokens()
stravaTokens.refreshIfNeeded()
minioClient, err := minio.New(secrets.SECRETS.MinioEndpoint, &minio.Options{
Expand All @@ -28,9 +29,9 @@ func Setup(router *chi.Mux) {
lumber.ErrorMsg("failed to load initial data for strava cache; not updating")
}
stravaCache := cache.New("strava", stravaActivities)
router.Get("/strava", stravaCache.ServeHTTP())
router.Post("/strava/event", eventRoute(stravaCache, *minioClient, stravaTokens))
router.Get("/strava/event", challengeRoute)
mux.HandleFunc("GET /strava", stravaCache.ServeHTTP)
mux.HandleFunc("POST /strava/event", eventRoute(stravaCache, *minioClient, stravaTokens))
mux.HandleFunc("GET /strava/event", challengeRoute)

lumber.Done("setup strava cache")
}
28 changes: 13 additions & 15 deletions internal/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,21 +40,19 @@ type CacheResponse[T any] struct {
Updated time.Time `json:"updated"`
}

func (c *Cache[T]) ServeHTTP() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !auth.IsAuthorized(w, r) {
return
}
w.Header().Set("Content-Type", "application/json")
c.DataMutex.RLock()
err := json.NewEncoder(w).Encode(CacheResponse[T]{Data: c.Data, Updated: c.Updated})
c.DataMutex.RUnlock()
if err != nil {
err = fmt.Errorf("%v failed to write json data to request", err)
lumber.Error(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
func (c *Cache[T]) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !auth.IsAuthorized(w, r) {
return
}
w.Header().Set("Content-Type", "application/json")
c.DataMutex.RLock()
err := json.NewEncoder(w).Encode(CacheResponse[T]{Data: c.Data, Updated: c.Updated})
c.DataMutex.RUnlock()
if err != nil {
err = fmt.Errorf("%v failed to write json data to request", err)
lumber.Error(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}

func (c *Cache[T]) Update(data T) {
Expand Down

0 comments on commit 59d024b

Please sign in to comment.