-
-
Notifications
You must be signed in to change notification settings - Fork 152
/
autoregister_test.go
53 lines (44 loc) · 1.4 KB
/
autoregister_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package huma_test
import (
"context"
"fmt"
"net/http"
"github.com/danielgtaylor/huma/v2"
"github.com/go-chi/chi/v5"
)
// Item represents a single item with a unique ID.
type Item struct {
ID string `json:"id"`
}
// ItemsResponse is a response containing a list of items.
type ItemsResponse struct {
Body []Item `json:"body"`
}
// ItemsHandler handles item-related CRUD operations.
type ItemsHandler struct{}
// RegisterListItems registers the `list-items` operation with the given API.
// Because the method starts with `Register` it will be automatically called
// by `huma.AutoRegister` down below.
func (s *ItemsHandler) RegisterListItems(api huma.API) {
// Register a list operation to get all the items.
huma.Register(api, huma.Operation{
OperationID: "list-items",
Method: http.MethodGet,
Path: "/items",
}, func(ctx context.Context, input *struct{}) (*ItemsResponse, error) {
resp := &ItemsResponse{}
resp.Body = []Item{{ID: "123"}}
return resp, nil
})
}
func ExampleAutoRegister() {
// Create the router and API.
router := chi.NewMux()
api := NewExampleAPI(router, huma.DefaultConfig("My Service", "1.0.0"))
// Create the item handler and register all of its operations.
itemsHandler := &ItemsHandler{}
huma.AutoRegister(api, itemsHandler)
// Confirm the list operation was registered.
fmt.Println(api.OpenAPI().Paths["/items"].Get.OperationID)
// Output: list-items
}