feat(14.2.1-01): add optional surf LocaleResolver seam

Look up a backpack-published resolver so a compiled translate plugin can
strip an enabled URL prefix and write a validated locale onto context.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Jakub Zych
2026-10-06 11:54:00 +02:00
parent bd0a27f59f
commit b2ce986604
7 changed files with 134 additions and 15 deletions

View File

@@ -0,0 +1,81 @@
package surf
import (
"net/http"
"net/http/httptest"
"testing"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/towel"
)
type stubLocaleResolver struct {
code string
rewriteTo string
}
func (s stubLocaleResolver) Resolve(http.ResponseWriter, *http.Request) string {
return s.code
}
func (s stubLocaleResolver) Rewrite(r *http.Request) *http.Request {
if s.rewriteTo == "" {
return r
}
clone := r.Clone(r.Context())
clone.URL.Path = s.rewriteTo
return clone
}
func TestLocaleResolverWritesValidatedCodeAndStripsPrefix(t *testing.T) {
cfg := writeHTTPConfig(t, "body_limits:\n default_bytes: 1024\n upload_bytes: 1024\n")
app := backpack.New(cfg)
if err := app.Publish[LocaleResolver](stubLocaleResolver{code: "pl", rewriteTo: "/posts"}); err != nil {
t.Fatal(err)
}
r := New(nil)
r.app = app
r.defaultBytes = 1024
r.BindPlugin("acme.blog")
var gotPath, gotLoc string
var ok bool
r.Get("/posts", func(w http.ResponseWriter, req *http.Request) {
gotPath = req.URL.Path
gotLoc, ok = towel.Locale(req.Context())
w.WriteHeader(http.StatusNoContent)
})
h, err := r.compile()
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodGet, "/pl/posts", nil)
req.Header.Set("Accept-Language", "de")
h.ServeHTTP(httptest.NewRecorder(), req)
if gotPath != "/posts" {
t.Fatalf("path = %q, want /posts", gotPath)
}
if !ok || gotLoc != "pl" {
t.Fatalf("locale = %q ok=%t, want pl from resolver", gotLoc, ok)
}
}
func TestLocaleAbsentResolverKeepsAcceptLanguage(t *testing.T) {
r := New(nil)
r.BindPlugin("acme.blog")
var gotLoc string
var ok bool
r.Get("/posts", func(w http.ResponseWriter, req *http.Request) {
gotLoc, ok = towel.Locale(req.Context())
w.WriteHeader(http.StatusNoContent)
})
h, err := r.compile()
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodGet, "/posts", nil)
req.Header.Set("Accept-Language", "pl")
h.ServeHTTP(httptest.NewRecorder(), req)
if !ok || gotLoc != "pl" {
t.Fatalf("locale = %q ok=%t, want pl from Accept-Language", gotLoc, ok)
}
}