Skip to content

Commit

Permalink
refactor: with cursor, remove chi!
Browse files Browse the repository at this point in the history
  • Loading branch information
kaihendry committed Mar 8, 2025
1 parent 752dd4b commit abea4e8
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 37 deletions.
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ go 1.24
require (
github.com/apex/gateway/v2 v2.0.0
github.com/fogleman/gg v1.3.0
github.com/go-chi/chi/v5 v5.2.1
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0
golang.org/x/image v0.25.0
)
Expand Down
10 changes: 0 additions & 10 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,6 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fogleman/gg v1.3.0 h1:/7zJX8F6AaYQc57WQCyN9cAIz+4bCJGO9B+dyW29am8=
github.com/fogleman/gg v1.3.0/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k=
github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw=
github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
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-chi/chi/v5 v5.2.1 h1:KOIHODQj58PmL80G2Eak4WdvUzjSJSm0vG72crDCqb8=
github.com/go-chi/chi/v5 v5.2.1/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
Expand All @@ -36,10 +30,6 @@ github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o
github.com/tj/assert v0.0.3 h1:Df/BlaZ20mq6kuai7f5z2TvPFiwC3xaWJSDQNiIS3Rk=
github.com/tj/assert v0.0.3/go.mod h1:Ne6X72Q+TB1AteidzQncjw9PabbMp4PBMZ1k+vd1Pvk=
github.com/urfave/cli/v2 v2.1.1/go.mod h1:SE9GqnLQmjVa0iPEY0f1w3ygNIYcIJ0OKPMoW2caLfQ=
golang.org/x/image v0.20.0 h1:7cVCUjQwfL18gyBJOmYvptfSHS8Fb3YUDtfLIZ7Nbpw=
golang.org/x/image v0.20.0/go.mod h1:0a88To4CYVBAHp5FXJm8o7QbUl37Vd85ply1vyD8auM=
golang.org/x/image v0.23.0 h1:HseQ7c2OpPKTPVzNjG5fwJsOTCiiwS4QdsYi5XU6H68=
golang.org/x/image v0.23.0/go.mod h1:wJJBTdLfCCf3tiHa1fNxpZmUI4mmoZvwMCPP0ddoNKY=
golang.org/x/image v0.25.0 h1:Y6uW6rH1y5y/LK1J8BPWZtr6yZ7hrsy6hFrXjgsc2fQ=
golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
Expand Down
101 changes: 75 additions & 26 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,14 @@ import (
"fmt"
"html/template"
"io/fs"
"log/slog"
"math"
"net/http"
"os"
"sort"
"strconv"
"time"

"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"

"log/slog"

"github.com/apex/gateway/v2"
)

Expand Down Expand Up @@ -52,10 +48,42 @@ type SGBusArrivals struct {
}

type Server struct {
router *chi.Mux
mux *http.ServeMux
busStops BusStops
}

type responseWriter struct {
http.ResponseWriter
status int
wroteHeader bool
bytes int
}

func (rw *responseWriter) WriteHeader(code int) {
if !rw.wroteHeader {
rw.status = code
rw.wroteHeader = true
rw.ResponseWriter.WriteHeader(code)
}
}

func (rw *responseWriter) Write(b []byte) (int, error) {
if !rw.wroteHeader {
rw.WriteHeader(http.StatusOK)
}
n, err := rw.ResponseWriter.Write(b)
rw.bytes += n
return n, err
}

func (rw *responseWriter) Status() int {
return rw.status
}

func (rw *responseWriter) BytesWritten() int {
return rw.bytes
}

func getLogger(logLevel string) *slog.Logger {
levelVar := slog.LevelVar{}

Expand Down Expand Up @@ -83,12 +111,14 @@ func main() {

slog.SetDefault(getLogger(os.Getenv("LOGLEVEL")))

handler := server.middlewareChain(server.mux)

if _, ok := os.LookupEnv("AWS_LAMBDA_FUNCTION_NAME"); ok {
slog.Info("starting server", "version", os.Getenv("VERSION"))
err = gateway.ListenAndServe("", server.router)
err = gateway.ListenAndServe("", handler)
} else {
slog.Info("starting local server", "version", os.Getenv("VERSION"), "port", os.Getenv("PORT"))
err = http.ListenAndServe(fmt.Sprintf(":%s", os.Getenv("PORT")), server.router)
err = http.ListenAndServe(fmt.Sprintf(":%s", os.Getenv("PORT")), handler)
}

slog.Error("error listening", "error", err)
Expand All @@ -101,28 +131,43 @@ func NewServer(busStopsPath string) (*Server, error) {
}

srv := Server{
router: chi.NewRouter(),
mux: http.NewServeMux(),
busStops: bs,
}

srv.router.Use(middleware.RequestID)
srv.router.Use(uniqueVisitor)
srv.router.Use(logRequest)
srv.router.Use(middleware.Recoverer)
srv.routes()

srv.router.Get("/", srv.handleIndex)
srv.router.Get("/closest", srv.handleClosest)
srv.router.Get("/icon", handleIcon)
return &srv, nil
}

func (s *Server) routes() {
s.mux.HandleFunc("/", s.handleIndex)
s.mux.HandleFunc("/closest", s.handleClosest)
s.mux.HandleFunc("/icon", handleIcon)

directory, err := fs.Sub(static, "static")
if err != nil {
slog.Error("unable to load static files", "error", err)
return
}
fileServer := http.FileServer(http.FS(directory))
//srv.router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fileServer))
srv.router.Mount("/static", http.StripPrefix("/static", fileServer))
s.mux.Handle("/static/", http.StripPrefix("/static/", fileServer))
}

return &srv, nil
func (s *Server) middlewareChain(handler http.Handler) http.Handler {
return logRequest(uniqueVisitor(recoverPanic(handler)))
}

func recoverPanic(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
slog.Error("recovered from panic", "error", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}

func (s *Server) handleClosest(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -299,10 +344,14 @@ func (p Point) distance(p2 Point) float64 {
func logRequest(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
rw := &responseWriter{
ResponseWriter: w,
status: http.StatusOK,
}

defer func() {
// Log response headers here
for name, values := range ww.Header() {
// Log response headers
for name, values := range rw.Header() {
for _, value := range values {
slog.Debug("response header", "name", name, "value", value)
}
Expand All @@ -312,13 +361,13 @@ func logRequest(next http.Handler) http.Handler {
"req_method", r.Method,
"req_ip", r.RemoteAddr,
"req_path", r.RequestURI,
"res_status", ww.Status(),
"res_size", ww.BytesWritten(),
"res_content_type", ww.Header().Get("Content-Type"),
"res_status", rw.Status(),
"res_size", rw.BytesWritten(),
"res_content_type", rw.Header().Get("Content-Type"),
"duration", time.Since(start).Milliseconds(),
)
}()
next.ServeHTTP(ww, r)
next.ServeHTTP(rw, r)
})
}

Expand Down

0 comments on commit abea4e8

Please sign in to comment.