docs(phrasebook,sieve,towel,wire,wristband): compile README Go examples via src= (quick-261118-qsd)
This commit is contained in:
@@ -44,37 +44,62 @@ count:
|
||||
other: ":count posts"
|
||||
```
|
||||
|
||||
```go
|
||||
package blog
|
||||
In the example `langFS` is an in-memory copy of that `lang/` tree; a plugin embeds its own with `//go:embed lang`.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"fmt"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||
"git.golem15.com/golem15/summercms/modules/towel"
|
||||
)
|
||||
|
||||
//go:embed lang
|
||||
var langFS embed.FS
|
||||
|
||||
func Example() error {
|
||||
cat := phrasebook.NewCatalog()
|
||||
if err := cat.Load("acme.blog", langFS); err != nil {
|
||||
return err
|
||||
}
|
||||
tr := phrasebook.NewTranslator(cat, phrasebook.Options{Locale: "en", Fallback: "en"})
|
||||
|
||||
ctx := towel.WithLocale(context.Background(), "en")
|
||||
fmt.Println(tr.Get(ctx, "acme.blog::posts.greeting", map[string]string{"name": "Ada"})) // Hello, Ada
|
||||
fmt.Println(tr.ChoiceIn("en", "acme.blog::posts.count", 3, nil)) // 3 posts
|
||||
return nil
|
||||
```go src=modules/phrasebook/example_test.go#ExampleTranslator_Get
|
||||
cat := phrasebook.NewCatalog()
|
||||
if err := cat.Load("acme.blog", langFS); err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
tr := phrasebook.NewTranslator(cat, phrasebook.Options{Locale: "en", Fallback: "en"})
|
||||
|
||||
// Inside a running application, use the translator published at boot.
|
||||
func Title(ctx context.Context, app *backpack.App) string {
|
||||
// surf stores the request locale on the context; here the example does.
|
||||
ctx := towel.WithLocale(context.Background(), "pl")
|
||||
fmt.Println(tr.Get(ctx, "acme.blog::posts.title", nil))
|
||||
// pl has no greeting, so the fallback locale answers.
|
||||
fmt.Println(tr.Get(ctx, "acme.blog::posts.greeting", map[string]string{"name": "Ada"}))
|
||||
fmt.Println(tr.GetIn("en", "acme.blog::posts.shout", map[string]string{"name": "Ada"}))
|
||||
// A missing key comes back as the key.
|
||||
fmt.Println(tr.Get(ctx, "acme.blog::posts.missing", nil))
|
||||
// Output:
|
||||
// Posty
|
||||
// Hello, Ada
|
||||
// Welcome, ADA
|
||||
// acme.blog::posts.missing
|
||||
```
|
||||
|
||||
```go src=modules/phrasebook/example_test.go#ExampleTranslator_Choice
|
||||
cat := phrasebook.NewCatalog()
|
||||
if err := cat.Load("acme.blog", langFS); err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
tr := phrasebook.NewTranslator(cat, phrasebook.Options{Locale: "en", Fallback: "en"})
|
||||
|
||||
for _, n := range []int{1, 3, 5, 22} {
|
||||
fmt.Println(tr.ChoiceIn("pl", "acme.blog::posts.count", n, nil))
|
||||
}
|
||||
fmt.Println(tr.ChoiceIn("en", "acme.blog::posts.count", 5, nil))
|
||||
for _, n := range []int{0, 1, 7} {
|
||||
fmt.Println(tr.ChoiceIn("en", "acme.blog::posts.drafts", n, nil))
|
||||
}
|
||||
// Output:
|
||||
// 1 post
|
||||
// 3 posty
|
||||
// 5 postów
|
||||
// 22 posty
|
||||
// 5 posts
|
||||
// No drafts
|
||||
// One draft
|
||||
// 7 drafts
|
||||
```
|
||||
|
||||
Inside a running application, use the translator published at boot:
|
||||
|
||||
```go src=modules/phrasebook/example_test.go#title
|
||||
// title reads the translator published at boot inside a running application.
|
||||
func title(ctx context.Context, app *backpack.App) string {
|
||||
tr, ok := app.Lookup[*phrasebook.Translator]()
|
||||
if !ok {
|
||||
return "acme.blog::posts.title"
|
||||
@@ -83,6 +108,7 @@ func Title(ctx context.Context, app *backpack.App) string {
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## API reference
|
||||
|
||||
| Identifier | Description |
|
||||
|
||||
@@ -3,8 +3,11 @@ package phrasebook_test
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"testing/fstest"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||
"git.golem15.com/golem15/summercms/modules/towel"
|
||||
)
|
||||
@@ -76,3 +79,33 @@ func ExampleTranslator_Choice() {
|
||||
// One draft
|
||||
// 7 drafts
|
||||
}
|
||||
|
||||
// title reads the translator published at boot inside a running application.
|
||||
func title(ctx context.Context, app *backpack.App) string {
|
||||
tr, ok := app.Lookup[*phrasebook.Translator]()
|
||||
if !ok {
|
||||
return "acme.blog::posts.title"
|
||||
}
|
||||
return tr.Get(ctx, "acme.blog::posts.title", nil)
|
||||
}
|
||||
|
||||
// blogPlugin ships its lang tree through pact.HasLang.
|
||||
type blogPlugin struct{}
|
||||
|
||||
func (blogPlugin) ID() string { return "acme.blog" }
|
||||
func (blogPlugin) LangFS() fs.FS { return langFS }
|
||||
|
||||
func ExampleActivate() {
|
||||
app := backpack.New(&compass.Config{})
|
||||
ctx := towel.WithLocale(context.Background(), "pl")
|
||||
fmt.Println(title(ctx, app)) // before boot: no translator yet
|
||||
|
||||
if err := phrasebook.Activate(app, []blogPlugin{{}}); err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
fmt.Println(title(ctx, app))
|
||||
// Output:
|
||||
// acme.blog::posts.title
|
||||
// Posty
|
||||
}
|
||||
|
||||
@@ -43,43 +43,40 @@ Use cases:
|
||||
|
||||
## Usage
|
||||
|
||||
```go
|
||||
package blog
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/sieve"
|
||||
)
|
||||
|
||||
type Post struct {
|
||||
```go src=modules/sieve/example_test.go#blogPost
|
||||
// blogPost is the model that shape filters, groups and reshapes.
|
||||
type blogPost struct {
|
||||
ID int
|
||||
Author string
|
||||
Title string
|
||||
Published bool
|
||||
}
|
||||
```
|
||||
|
||||
type PostResponse struct {
|
||||
```go src=modules/sieve/example_test.go#postResponse
|
||||
// postResponse is the JSON shape of one post in a list response.
|
||||
type postResponse struct {
|
||||
ID int `json:"id"`
|
||||
Title string `json:"title"`
|
||||
}
|
||||
```
|
||||
|
||||
func shape(posts []Post, rawIDs []string) error {
|
||||
```go src=modules/sieve/example_test.go#shape
|
||||
func shape(posts []blogPost, rawIDs []string) error {
|
||||
// Keep the published posts and turn them into response structs.
|
||||
published := sieve.Filter(posts, func(p Post) bool { return p.Published })
|
||||
body := sieve.Map(published, func(p Post) PostResponse {
|
||||
return PostResponse{ID: p.ID, Title: p.Title}
|
||||
published := sieve.Filter(posts, func(p blogPost) bool { return p.Published })
|
||||
body := sieve.Map(published, func(p blogPost) postResponse {
|
||||
return postResponse{ID: p.ID, Title: p.Title}
|
||||
})
|
||||
|
||||
// Key by ID for lookups, group by author, keep one post per author.
|
||||
byID := sieve.KeyBy(posts, func(p Post) int { return p.ID })
|
||||
byAuthor := sieve.GroupBy(posts, func(p Post) string { return p.Author })
|
||||
firstPerAuthor := sieve.UniqBy(posts, func(p Post) string { return p.Author })
|
||||
byID := sieve.KeyBy(posts, func(p blogPost) int { return p.ID })
|
||||
byAuthor := sieve.GroupBy(posts, func(p blogPost) string { return p.Author })
|
||||
firstPerAuthor := sieve.UniqBy(posts, func(p blogPost) string { return p.Author })
|
||||
|
||||
// Split drafts from published posts, and find the first draft.
|
||||
live, drafts := sieve.Partition(posts, func(p Post) bool { return p.Published })
|
||||
firstDraft, found := sieve.Find(posts, func(p Post) bool { return !p.Published })
|
||||
live, drafts := sieve.Partition(posts, func(p blogPost) bool { return p.Published })
|
||||
firstDraft, found := sieve.Find(posts, func(p blogPost) bool { return !p.Published })
|
||||
|
||||
// Parse IDs from a query string, stopping at the first bad one.
|
||||
ids, err := sieve.TryMap(rawIDs, strconv.Atoi)
|
||||
@@ -94,7 +91,21 @@ func shape(posts []Post, rawIDs []string) error {
|
||||
}
|
||||
```
|
||||
|
||||
There is no Pluck. Laravel's `pluck('title')` takes a field name as a string, which in Go would need reflection and would give up compile-time type checking. The typed equivalent is `sieve.Map(posts, func(p Post) string { return p.Title })`.
|
||||
```go src=modules/sieve/example_test.go#Example_shape
|
||||
posts := []blogPost{
|
||||
{ID: 1, Author: "ana", Title: "Hello", Published: true},
|
||||
{ID: 2, Author: "bob", Title: "Summer"},
|
||||
{ID: 3, Author: "ana", Title: "Goodbye", Published: true},
|
||||
}
|
||||
fmt.Println(shape(posts, []string{"1", "3"}))
|
||||
fmt.Println(shape(posts, []string{"1", "x"}))
|
||||
// Output:
|
||||
// 2 3 2 2 2 1 Summer true true
|
||||
// <nil>
|
||||
// blog: bad post id: strconv.Atoi: parsing "x": invalid syntax
|
||||
```
|
||||
|
||||
There is no Pluck. Laravel's `pluck('title')` takes a field name as a string, which in Go would need reflection and would give up compile-time type checking. The typed equivalent is `sieve.Map(posts, func(p blogPost) string { return p.Title })`.
|
||||
|
||||
What the standard library already covers:
|
||||
|
||||
|
||||
@@ -124,3 +124,59 @@ func ExampleSet_Slice() {
|
||||
fmt.Println(ids)
|
||||
// Output: [1 2 3]
|
||||
}
|
||||
|
||||
// blogPost is the model that shape filters, groups and reshapes.
|
||||
type blogPost struct {
|
||||
ID int
|
||||
Author string
|
||||
Title string
|
||||
Published bool
|
||||
}
|
||||
|
||||
// postResponse is the JSON shape of one post in a list response.
|
||||
type postResponse struct {
|
||||
ID int `json:"id"`
|
||||
Title string `json:"title"`
|
||||
}
|
||||
|
||||
func shape(posts []blogPost, rawIDs []string) error {
|
||||
// Keep the published posts and turn them into response structs.
|
||||
published := sieve.Filter(posts, func(p blogPost) bool { return p.Published })
|
||||
body := sieve.Map(published, func(p blogPost) postResponse {
|
||||
return postResponse{ID: p.ID, Title: p.Title}
|
||||
})
|
||||
|
||||
// Key by ID for lookups, group by author, keep one post per author.
|
||||
byID := sieve.KeyBy(posts, func(p blogPost) int { return p.ID })
|
||||
byAuthor := sieve.GroupBy(posts, func(p blogPost) string { return p.Author })
|
||||
firstPerAuthor := sieve.UniqBy(posts, func(p blogPost) string { return p.Author })
|
||||
|
||||
// Split drafts from published posts, and find the first draft.
|
||||
live, drafts := sieve.Partition(posts, func(p blogPost) bool { return p.Published })
|
||||
firstDraft, found := sieve.Find(posts, func(p blogPost) bool { return !p.Published })
|
||||
|
||||
// Parse IDs from a query string, stopping at the first bad one.
|
||||
ids, err := sieve.TryMap(rawIDs, strconv.Atoi)
|
||||
if err != nil {
|
||||
return fmt.Errorf("blog: bad post id: %w", err)
|
||||
}
|
||||
wanted := sieve.SetOf(ids...)
|
||||
|
||||
fmt.Println(len(body), len(byID), len(byAuthor), len(firstPerAuthor),
|
||||
len(live), len(drafts), firstDraft.Title, found, wanted.Has(1))
|
||||
return nil
|
||||
}
|
||||
|
||||
func Example_shape() {
|
||||
posts := []blogPost{
|
||||
{ID: 1, Author: "ana", Title: "Hello", Published: true},
|
||||
{ID: 2, Author: "bob", Title: "Summer"},
|
||||
{ID: 3, Author: "ana", Title: "Goodbye", Published: true},
|
||||
}
|
||||
fmt.Println(shape(posts, []string{"1", "3"}))
|
||||
fmt.Println(shape(posts, []string{"1", "x"}))
|
||||
// Output:
|
||||
// 2 3 2 2 2 1 Summer true true
|
||||
// <nil>
|
||||
// blog: bad post id: strconv.Atoi: parsing "x": invalid syntax
|
||||
}
|
||||
|
||||
@@ -29,16 +29,7 @@ Use cases:
|
||||
|
||||
## Usage
|
||||
|
||||
```go
|
||||
package blog
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/towel"
|
||||
)
|
||||
|
||||
```go src=modules/towel/example_test.go#withAcmeScope
|
||||
// withAcmeScope tags every request with the organization and collection it serves.
|
||||
func withAcmeScope(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -47,7 +38,9 @@ func withAcmeScope(next http.Handler) http.Handler {
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
```go src=modules/towel/example_test.go#listPosts
|
||||
func listPosts(w http.ResponseWriter, r *http.Request) {
|
||||
org, _ := towel.Organization(r.Context())
|
||||
locale, ok := towel.Locale(r.Context())
|
||||
@@ -58,6 +51,23 @@ func listPosts(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
```
|
||||
|
||||
```go src=modules/towel/example_test.go#ExampleWithLocale
|
||||
// surf sets the locale from Accept-Language; here the test sets it.
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/blog/posts", nil)
|
||||
req = req.WithContext(towel.WithLocale(req.Context(), "pl"))
|
||||
rec := httptest.NewRecorder()
|
||||
withAcmeScope(http.HandlerFunc(listPosts)).ServeHTTP(rec, req)
|
||||
fmt.Print(rec.Body.String())
|
||||
|
||||
// Without a locale the handler falls back to English.
|
||||
rec = httptest.NewRecorder()
|
||||
withAcmeScope(http.HandlerFunc(listPosts)).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/blog/posts", nil))
|
||||
fmt.Print(rec.Body.String())
|
||||
// Output:
|
||||
// posts for acme in pl
|
||||
// posts for acme in en
|
||||
```
|
||||
|
||||
## API reference
|
||||
|
||||
| Identifier | Description |
|
||||
|
||||
@@ -8,30 +8,47 @@ import (
|
||||
"git.golem15.com/golem15/summercms/modules/towel"
|
||||
)
|
||||
|
||||
func ExampleWithLocale() {
|
||||
// A middleware stores the organization once for the whole request.
|
||||
withAcme := func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := towel.WithOrganization(r.Context(), "acme")
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// The handler reads the values back from its request context.
|
||||
listPosts := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
org, _ := towel.Organization(r.Context())
|
||||
locale, ok := towel.Locale(r.Context())
|
||||
if !ok {
|
||||
locale = "en"
|
||||
}
|
||||
fmt.Fprintf(w, "posts for %s in %s", org, locale)
|
||||
// withAcmeScope tags every request with the organization and collection it serves.
|
||||
func withAcmeScope(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := towel.WithOrganization(r.Context(), "acme")
|
||||
ctx = towel.WithCollection(ctx, "blog")
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func listPosts(w http.ResponseWriter, r *http.Request) {
|
||||
org, _ := towel.Organization(r.Context())
|
||||
locale, ok := towel.Locale(r.Context())
|
||||
if !ok {
|
||||
locale = "en"
|
||||
}
|
||||
fmt.Fprintf(w, "posts for %s in %s\n", org, locale)
|
||||
}
|
||||
|
||||
func ExampleWithLocale() {
|
||||
// surf sets the locale from Accept-Language; here the test sets it.
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/blog/posts", nil)
|
||||
req = req.WithContext(towel.WithLocale(req.Context(), "pl"))
|
||||
rec := httptest.NewRecorder()
|
||||
withAcme(listPosts).ServeHTTP(rec, req)
|
||||
fmt.Println(rec.Body.String())
|
||||
// Output: posts for acme in pl
|
||||
withAcmeScope(http.HandlerFunc(listPosts)).ServeHTTP(rec, req)
|
||||
fmt.Print(rec.Body.String())
|
||||
|
||||
// Without a locale the handler falls back to English.
|
||||
rec = httptest.NewRecorder()
|
||||
withAcmeScope(http.HandlerFunc(listPosts)).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/blog/posts", nil))
|
||||
fmt.Print(rec.Body.String())
|
||||
// Output:
|
||||
// posts for acme in pl
|
||||
// posts for acme in en
|
||||
}
|
||||
|
||||
// ExampleWithCollection reads the collection withAcmeScope stores.
|
||||
func ExampleWithCollection() {
|
||||
var collection string
|
||||
withAcmeScope(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
collection, _ = towel.Collection(r.Context())
|
||||
})).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil))
|
||||
fmt.Println(collection)
|
||||
// Output: blog
|
||||
}
|
||||
|
||||
@@ -30,35 +30,41 @@ Use cases:
|
||||
|
||||
## Usage
|
||||
|
||||
```go
|
||||
package blog
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/wire"
|
||||
)
|
||||
|
||||
```go src=modules/wire/example_test.go#postJSON
|
||||
// postJSON is the response shape of one acme.blog post.
|
||||
type postJSON struct {
|
||||
ID uint `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Tags []string `json:"tags"`
|
||||
Featured wire.TriBool `json:"featured"`
|
||||
Pinned wire.TriBool `json:"pinned"`
|
||||
PublishedAt wire.Time `json:"published_at"`
|
||||
}
|
||||
```
|
||||
|
||||
func showPost(w http.ResponseWriter, r *http.Request) {
|
||||
var tags []string // nil when the post has no tags
|
||||
body := postJSON{
|
||||
ID: 1,
|
||||
Title: "Hello & welcome", // "&" stays unescaped
|
||||
Tags: wire.Slice(tags), // marshals as []
|
||||
Featured: wire.TriBool{}, // marshals as null
|
||||
PublishedAt: wire.Time{Time: time.Now()}, // "...+00:00"
|
||||
}
|
||||
wire.WriteJSON(w, http.StatusOK, map[string]any{"data": body})
|
||||
```go src=modules/wire/example_test.go#ExampleWriteJSON
|
||||
var tags []string // nil: the post has no tags
|
||||
warsaw := time.FixedZone("CEST", 2*60*60)
|
||||
body := postJSON{
|
||||
ID: 1,
|
||||
Title: "Tips & <tricks>",
|
||||
Tags: wire.Slice(tags),
|
||||
Featured: wire.TriBool{},
|
||||
Pinned: wire.TriBool{Value: true, Valid: true},
|
||||
PublishedAt: wire.Time{Time: time.Date(2026, 9, 30, 14, 5, 0, 0, warsaw)},
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
wire.WriteJSON(rec, http.StatusOK, map[string]any{"data": body})
|
||||
fmt.Println(rec.Code, rec.Header().Get("Content-Type"))
|
||||
fmt.Printf("%s|\n", rec.Body.String())
|
||||
|
||||
rec = httptest.NewRecorder()
|
||||
wire.WriteOpaque500(rec)
|
||||
fmt.Println(rec.Code, rec.Body.String())
|
||||
// Output:
|
||||
// 200 application/json
|
||||
// {"data":{"id":1,"title":"Tips & <tricks>","tags":[],"featured":null,"pinned":true,"published_at":"2026-09-30T12:05:00+00:00"}}|
|
||||
// 500 {"error":true,"message":"Internal server error"}
|
||||
```
|
||||
|
||||
## API reference
|
||||
|
||||
@@ -41,19 +41,11 @@ Use cases:
|
||||
|
||||
## Usage
|
||||
|
||||
```go
|
||||
package oauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/wristband"
|
||||
)
|
||||
|
||||
func NewServer(backend wristband.Backend) *wristband.Server {
|
||||
```go src=modules/wristband/example_test.go#newServer
|
||||
// newServer builds the authorization server of an application served at
|
||||
// https://blog.example.com. The application sets Issuer and Resource for
|
||||
// its own deployment; the defaults cover everything else.
|
||||
func newServer(backend wristband.Backend) *wristband.Server {
|
||||
opts := wristband.DefaultOptions()
|
||||
opts.Issuer = "https://blog.example.com" // app URL without a trailing slash
|
||||
opts.Resource = "https://blog.example.com/mcp"
|
||||
@@ -63,9 +55,11 @@ func NewServer(backend wristband.Backend) *wristband.Server {
|
||||
srv.SetBackend(backend) // the application's transactional store adapter
|
||||
return srv
|
||||
}
|
||||
```
|
||||
|
||||
// Routes mounts the RFC endpoints in a raw group: no JSON envelope middleware.
|
||||
func Routes(r pact.Router, srv *wristband.Server) {
|
||||
```go src=modules/wristband/example_test.go#routes
|
||||
// routes mounts the RFC endpoints in a raw group: no JSON envelope middleware.
|
||||
func routes(r pact.Router, srv *wristband.Server) {
|
||||
r.GroupRaw("", nil, func(g pact.Router) {
|
||||
g.Get("/.well-known/oauth-authorization-server", srv.Metadata)
|
||||
g.Get("/oauth/mcp/authorize", srv.Authorize)
|
||||
@@ -73,9 +67,11 @@ func Routes(r pact.Router, srv *wristband.Server) {
|
||||
g.Post("/oauth/mcp/register", srv.Register)
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
// Approve is called by the application's consent handler for a signed-in user.
|
||||
func Approve(ctx context.Context, w http.ResponseWriter, srv *wristband.Server, requestID string, userID uint) error {
|
||||
```go src=modules/wristband/example_test.go#approve
|
||||
// approve is called by the application's consent handler for a signed-in user.
|
||||
func approve(ctx context.Context, w http.ResponseWriter, srv *wristband.Server, requestID string, userID uint) error {
|
||||
redirectTo, err := srv.IssueCode(ctx, requestID, userID, []string{"read"}, nil)
|
||||
if err != nil {
|
||||
return err // wristband.ErrPendingNotFound, wristband.ErrNoGrantableScopes, ...
|
||||
@@ -85,15 +81,20 @@ func Approve(ctx context.Context, w http.ResponseWriter, srv *wristband.Server,
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
The OpenID Connect flavour is a second server on the same engine. The host (usually a shared plugin) implements `wristband.OIDCBackend`, `wristband.KeyStore` and `wristband.OIDCHost`, then mounts the handlers at the paths discovery advertises:
|
||||
|
||||
```go
|
||||
func NewProvider(backend wristband.OIDCBackend, keys wristband.KeyStore, host wristband.OIDCHost) (*wristband.Server, error) {
|
||||
```go src=modules/wristband/example_test.go#newOIDCServer
|
||||
// newOIDCServer builds the OpenID Connect provider of an application served
|
||||
// at https://id.example.com. The host application supplies storage, the
|
||||
// signing-key ring and its pages; SetOIDCBackend refuses a nil one.
|
||||
func newOIDCServer(backend wristband.OIDCBackend, keys wristband.KeyStore, host wristband.OIDCHost) (*wristband.Server, error) {
|
||||
opts := wristband.DefaultOptions()
|
||||
opts.Issuer = "https://id.example.com"
|
||||
|
||||
oidc := wristband.DefaultOIDCOptions()
|
||||
oidc.LoginURL = "/account/login" // anonymous users land here with ?redirect=<resume path>
|
||||
oidc.RefreshEnabled = true // only clients with OfflineAccess get refresh tokens
|
||||
|
||||
srv := wristband.NewOIDCServer(opts, oidc)
|
||||
if err := srv.SetOIDCBackend(backend, keys, host); err != nil {
|
||||
@@ -101,8 +102,12 @@ func NewProvider(backend wristband.OIDCBackend, keys wristband.KeyStore, host wr
|
||||
}
|
||||
return srv, nil
|
||||
}
|
||||
```
|
||||
|
||||
func ProviderRoutes(r pact.Router, srv *wristband.Server) {
|
||||
```go src=modules/wristband/example_test.go#providerRoutes
|
||||
// providerRoutes mounts the OpenID Connect endpoints at the paths discovery
|
||||
// advertises.
|
||||
func providerRoutes(r pact.Router, srv *wristband.Server) {
|
||||
r.GroupRaw("", nil, func(g pact.Router) {
|
||||
g.Get("/.well-known/openid-configuration", srv.Discovery)
|
||||
g.Get("/oauth/jwks", srv.JWKS)
|
||||
@@ -116,6 +121,7 @@ func ProviderRoutes(r pact.Router, srv *wristband.Server) {
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
`wristband.OIDCHost.RenderConsent` receives a `wristband.ConsentView`; the page posts `request_id`, `consent_token` and `decision` (`allow` or anything else) back to `POST /oauth/authorize`, or `request_id` and `consent_token` to the switch-account route. A host whose consent page lives in its own frontend redirects there from `wristband.OIDCHost.RenderConsent` and finishes through `wristband.Server.ConsentRequest` and `wristband.Server.DecideConsent`.
|
||||
|
||||
## API reference
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
package wristband_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/wristband"
|
||||
)
|
||||
@@ -11,18 +19,40 @@ import (
|
||||
// newServer builds the authorization server of an application served at
|
||||
// https://blog.example.com. The application sets Issuer and Resource for
|
||||
// its own deployment; the defaults cover everything else.
|
||||
func newServer() *wristband.Server {
|
||||
func newServer(backend wristband.Backend) *wristband.Server {
|
||||
opts := wristband.DefaultOptions()
|
||||
opts.Issuer = "https://blog.example.com"
|
||||
opts.Issuer = "https://blog.example.com" // app URL without a trailing slash
|
||||
opts.Resource = "https://blog.example.com/mcp"
|
||||
opts.ScopesSupported = []string{"read", "write", "offline_access"}
|
||||
return wristband.NewServer(opts)
|
||||
|
||||
srv := wristband.NewServer(opts)
|
||||
srv.SetBackend(backend) // the application's transactional store adapter
|
||||
return srv
|
||||
}
|
||||
|
||||
// routes mounts the RFC endpoints in a raw group: no JSON envelope middleware.
|
||||
func routes(r pact.Router, srv *wristband.Server) {
|
||||
r.GroupRaw("", nil, func(g pact.Router) {
|
||||
g.Get("/.well-known/oauth-authorization-server", srv.Metadata)
|
||||
g.Get("/oauth/mcp/authorize", srv.Authorize)
|
||||
g.Post("/oauth/mcp/token", srv.Token)
|
||||
g.Post("/oauth/mcp/register", srv.Register)
|
||||
})
|
||||
}
|
||||
|
||||
// approve is called by the application's consent handler for a signed-in user.
|
||||
func approve(ctx context.Context, w http.ResponseWriter, srv *wristband.Server, requestID string, userID uint) error {
|
||||
redirectTo, err := srv.IssueCode(ctx, requestID, userID, []string{"read"}, nil)
|
||||
if err != nil {
|
||||
return err // wristband.ErrPendingNotFound, wristband.ErrNoGrantableScopes, ...
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
return json.NewEncoder(w).Encode(map[string]string{"redirect_to": redirectTo})
|
||||
}
|
||||
|
||||
func ExampleServer_Metadata() {
|
||||
srv := newServer()
|
||||
// srv.SetBackend(backend) attaches the application's stores; the
|
||||
// metadata document does not need them.
|
||||
// The metadata document does not need the application's stores.
|
||||
srv := newServer(nil)
|
||||
rec := httptest.NewRecorder()
|
||||
srv.Metadata(rec, httptest.NewRequest("GET", "/.well-known/oauth-authorization-server", nil))
|
||||
|
||||
@@ -91,12 +121,12 @@ func newOIDCServer(backend wristband.OIDCBackend, keys wristband.KeyStore, host
|
||||
opts.Issuer = "https://id.example.com"
|
||||
|
||||
oidc := wristband.DefaultOIDCOptions()
|
||||
oidc.LoginURL = "/account/login"
|
||||
oidc.RefreshEnabled = true // only clients with OfflineAccess get refresh tokens
|
||||
oidc.LoginURL = "/account/login" // anonymous users land here with ?redirect=<resume path>
|
||||
oidc.RefreshEnabled = true // only clients with OfflineAccess get refresh tokens
|
||||
|
||||
srv := wristband.NewOIDCServer(opts, oidc)
|
||||
if err := srv.SetOIDCBackend(backend, keys, host); err != nil {
|
||||
return nil, err
|
||||
return nil, err // nil argument, or called on an MCP server
|
||||
}
|
||||
return srv, nil
|
||||
}
|
||||
@@ -119,3 +149,103 @@ func ExampleNewOIDCServer() {
|
||||
// metadata 404
|
||||
// [openid profile email] 1m0s false
|
||||
}
|
||||
|
||||
// providerRoutes mounts the OpenID Connect endpoints at the paths discovery
|
||||
// advertises.
|
||||
func providerRoutes(r pact.Router, srv *wristband.Server) {
|
||||
r.GroupRaw("", nil, func(g pact.Router) {
|
||||
g.Get("/.well-known/openid-configuration", srv.Discovery)
|
||||
g.Get("/oauth/jwks", srv.JWKS)
|
||||
g.Get("/oauth/authorize", srv.Authorize) // start
|
||||
g.Post("/oauth/authorize", srv.Authorize) // consent decision
|
||||
g.Get("/oauth/authorize/resume/{request}", srv.Resume)
|
||||
g.Post("/oauth/authorize/switch-account", srv.SwitchAccount)
|
||||
g.Post("/oauth/token", srv.Token)
|
||||
g.Get("/oauth/userinfo", srv.UserInfo)
|
||||
})
|
||||
}
|
||||
|
||||
// muxRouter is a minimal pact.Router over http.ServeMux, standing in for
|
||||
// surf's router in these tests. Middleware names are ignored.
|
||||
type muxRouter struct {
|
||||
mux *http.ServeMux
|
||||
prefix string
|
||||
}
|
||||
|
||||
func (m muxRouter) handle(method, path string, h http.HandlerFunc) {
|
||||
m.mux.HandleFunc(method+" "+m.prefix+path, h)
|
||||
}
|
||||
|
||||
func (m muxRouter) Group(prefix string, _ []string, fn func(pact.Router)) {
|
||||
fn(muxRouter{m.mux, m.prefix + prefix})
|
||||
}
|
||||
func (m muxRouter) GroupRaw(prefix string, mw []string, fn func(pact.Router)) {
|
||||
m.Group(prefix, mw, fn)
|
||||
}
|
||||
func (m muxRouter) Get(path string, h http.HandlerFunc, _ ...string) { m.handle("GET", path, h) }
|
||||
func (m muxRouter) Post(path string, h http.HandlerFunc, _ ...string) { m.handle("POST", path, h) }
|
||||
func (m muxRouter) Put(path string, h http.HandlerFunc, _ ...string) { m.handle("PUT", path, h) }
|
||||
func (m muxRouter) Patch(path string, h http.HandlerFunc, _ ...string) { m.handle("PATCH", path, h) }
|
||||
func (m muxRouter) Delete(path string, h http.HandlerFunc, _ ...string) { m.handle("DELETE", path, h) }
|
||||
func (muxRouter) Where(string, string) {}
|
||||
func (muxRouter) WhereIn(string, ...string) {}
|
||||
|
||||
func serve(t *testing.T, mux http.Handler, method, path string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
mux.ServeHTTP(rec, httptest.NewRequest(method, path, nil))
|
||||
return rec
|
||||
}
|
||||
|
||||
// TestDocsRoutes mounts the README's MCP and OpenID Connect routes and calls
|
||||
// the metadata, discovery and JWKS endpoints through them.
|
||||
func TestDocsRoutes(t *testing.T) {
|
||||
backend, _ := wristband.DocsBackend(t)
|
||||
mux := http.NewServeMux()
|
||||
routes(muxRouter{mux: mux}, newServer(backend))
|
||||
rec := serve(t, mux, http.MethodGet, "/.well-known/oauth-authorization-server")
|
||||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"issuer":"https://blog.example.com"`) {
|
||||
t.Fatalf("metadata: %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
|
||||
provider, err := newOIDCServer(wristband.DocsOIDC(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oidcMux := http.NewServeMux()
|
||||
providerRoutes(muxRouter{mux: oidcMux}, provider)
|
||||
rec = serve(t, oidcMux, http.MethodGet, "/.well-known/openid-configuration")
|
||||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"issuer":"https://id.example.com"`) {
|
||||
t.Fatalf("discovery: %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
rec = serve(t, oidcMux, http.MethodGet, "/oauth/jwks")
|
||||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"keys"`) {
|
||||
t.Fatalf("jwks: %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDocsApprove grants a pending request through approve and checks the
|
||||
// redirect it returns; a second approval finds the request used.
|
||||
func TestDocsApprove(t *testing.T) {
|
||||
backend, requestID := wristband.DocsBackend(t)
|
||||
srv := newServer(backend)
|
||||
rec := httptest.NewRecorder()
|
||||
if err := approve(context.Background(), rec, srv, requestID, 7); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var body map[string]string
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
redirect, err := url.Parse(body["redirect_to"])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
q := redirect.Query()
|
||||
if redirect.Host != "client.example.org" || q.Get("code") == "" || q.Get("iss") != "https://blog.example.com" || q.Get("state") != "docs-state" {
|
||||
t.Fatalf("redirect_to = %q", body["redirect_to"])
|
||||
}
|
||||
if err := approve(context.Background(), httptest.NewRecorder(), srv, requestID, 7); !errors.Is(err, wristband.ErrPendingNotFound) {
|
||||
t.Fatalf("second approve: %v, want ErrPendingNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
53
modules/wristband/export_docs_test.go
Normal file
53
modules/wristband/export_docs_test.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package wristband
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DocsBackend returns the in-memory MCP backend of this package's tests,
|
||||
// holding one public client and one pending authorization request, and
|
||||
// that request's id, for the docs examples in example_test.go.
|
||||
func DocsBackend(t *testing.T) (Backend, string) {
|
||||
t.Helper()
|
||||
b := newMemoryBackend()
|
||||
ctx := context.Background()
|
||||
const requestID = "docs-request"
|
||||
err := b.WithinTx(ctx, func(tx Tx) error {
|
||||
client := &ClientRecord{
|
||||
ClientID: "docs-client",
|
||||
ClientName: "Docs Client",
|
||||
RedirectURIs: []string{"https://client.example.org/callback"},
|
||||
TokenEndpointAuthMethod: "none",
|
||||
}
|
||||
if err := tx.CreateWithCap(ctx, client, 200); err != nil {
|
||||
return err
|
||||
}
|
||||
state, id := "docs-state", requestID
|
||||
return tx.CreatePending(ctx, &AuthCodeRecord{
|
||||
ClientID: client.ClientID,
|
||||
RedirectURI: "https://client.example.org/callback",
|
||||
Scopes: []string{"read", "write"},
|
||||
CodeChallenge: strings.Repeat("a", 43),
|
||||
CodeChallengeMethod: "S256",
|
||||
State: &state,
|
||||
RequestID: &id,
|
||||
ExpiresAt: time.Now().Add(10 * time.Minute),
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b, requestID
|
||||
}
|
||||
|
||||
// DocsOIDC returns the in-memory OpenID Connect storage, a key ring with
|
||||
// one RS256 key and a host fake, for the docs examples in example_test.go.
|
||||
func DocsOIDC(t *testing.T) (OIDCBackend, KeyStore, OIDCHost) {
|
||||
t.Helper()
|
||||
keys := newMemoryKeyStore()
|
||||
keys.rotate(t, AlgRS256, time.Now())
|
||||
return newMemoryOIDCBackend(), keys, &fakeOIDCHost{}
|
||||
}
|
||||
Reference in New Issue
Block a user