feat(api): add cors middleware with configurable origins

- wrap all routes with CORS, honoring KRPLY_CORS_ORIGINS (default *)
- short-circuit preflight OPTIONS and echo allowed origins
- honor the PORT env var for platform deployments (render etc)
This commit is contained in:
lakshit verma 2026-08-06 05:53:41 +05:30
parent 6576672b1d
commit 9155ea248c
No known key found for this signature in database
GPG key ID: EB498AFC60A7A01A
3 changed files with 92 additions and 11 deletions

View file

@ -42,6 +42,17 @@ func run() error {
return nil
}
listenAddr := *listen
listenFlagSet := false
flag.Visit(func(f *flag.Flag) {
if f.Name == "listen" {
listenFlagSet = true
}
})
if !listenFlagSet && os.Getenv("PORT") != "" {
listenAddr = ":" + os.Getenv("PORT")
}
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, nil)))
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
@ -64,11 +75,11 @@ func run() error {
return fmt.Errorf("build api server: %w", err)
}
httpSrv := &http.Server{Addr: *listen, Handler: srv.Handler()}
httpSrv := &http.Server{Addr: listenAddr, Handler: srv.Handler()}
errCh := make(chan error, 1)
go func() {
slog.Info("krply-server listening", "addr", *listen, "store", *storePath, "version", version)
slog.Info("krply-server listening", "addr", listenAddr, "store", *storePath, "version", version)
errCh <- httpSrv.ListenAndServe()
}()