switch to json slog

This commit is contained in:
Travis Shears 2025-09-26 21:12:29 +02:00
parent e172609039
commit 1c7341499a
3 changed files with 17 additions and 5 deletions

2
dev.sh
View file

@ -2,4 +2,4 @@
set -e set -e
go run main.go -cert=./keys/cert.crt.pem -key=./keys/localhost_key.pem -host=localhost:8080 go run main.go -cert=./keys/localhost.crt.pem -key=./keys/localhost_key.pem -host=localhost:8080

18
main.go
View file

@ -4,7 +4,8 @@ import (
"errors" "errors"
"flag" "flag"
"fmt" "fmt"
"log" "log/slog"
"os"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@ -16,7 +17,9 @@ type ExampleHandler struct {
} }
func (h ExampleHandler) ServeGemini(w gemini.ResponseWriter, req *gemini.Request) { func (h ExampleHandler) ServeGemini(w gemini.ResponseWriter, req *gemini.Request) {
log.Printf("request: %s, user: %v", req.URL.Path, strings.Join(userName(req), " ")) slog.Info("gemini request",
"path", req.URL.Path,
"user", strings.Join(userName(req), " "))
switch req.URL.Path { switch req.URL.Path {
case "/": case "/":
gemini.ServeFileName("pages/home.gmi", "text/gemini")(w, req) gemini.ServeFileName("pages/home.gmi", "text/gemini")(w, req)
@ -76,7 +79,13 @@ func userName(r *gemini.Request) []string {
} }
func main() { func main() {
println("Starting gemini server") // Set up structured JSON logging
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelInfo,
}))
slog.SetDefault(logger)
slog.Info("Starting gemini server")
var host, cert, key string var host, cert, key string
flag.StringVar(&host, "host", ":1965", "listen on host and port. Example: hostname:1965") flag.StringVar(&host, "host", ":1965", "listen on host and port. Example: hostname:1965")
flag.StringVar(&cert, "cert", "server.crt.pem", "certificate file") flag.StringVar(&cert, "cert", "server.crt.pem", "certificate file")
@ -87,6 +96,7 @@ func main() {
err := gemini.ListenAndServe(host, cert, key, gemini.TrapPanic(handler.ServeGemini)) err := gemini.ListenAndServe(host, cert, key, gemini.TrapPanic(handler.ServeGemini))
if err != nil { if err != nil {
log.Fatal(err) slog.Error("server failed to start", "error", err)
os.Exit(1)
} }
} }

View file

@ -48,3 +48,5 @@ Took quite some tinkering to get everything working, but it's finally up and run
You can find the source code for this capsule here: You can find the source code for this capsule here:
=> https://git.travisshears.com/travisshears/personal-gemini-capsule => https://git.travisshears.com/travisshears/personal-gemini-capsule
Diagram created with:
=> https://asciiflow.com