Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add param re-use example, fixes #94 #146

Merged
merged 1 commit into from
Oct 20, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions examples/param-reuse/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// This example shows how to reuse a parameter in the path and body.
//
// # Example call
// restish post :8888/reuse/leon
package main

import (
"context"
"fmt"
"net/http"

"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humachi"
"github.com/go-chi/chi/v5"
)

// Options for the CLI.
type Options struct {
Port int `help:"Port to listen on" default:"8888"`
}

// ReusableParam is a reusable parameter that can go in the path or the body
// of a request or response. The same validation applies to both places.
type ReusableParam struct {
User string `json:"user" path:"user" maxLength:"10"`
}

type MyResponse struct {
Body struct {
// Example use as a body field.
ReusableParam
}
}

func main() {
// Create a CLI app which takes a port option.
cli := huma.NewCLI(func(hooks huma.Hooks, options *Options) {
// Create a new router & API
router := chi.NewMux()
api := humachi.New(router, huma.DefaultConfig("My API", "1.0.0"))

huma.Register(api, huma.Operation{
OperationID: "reuse",
Method: http.MethodPost,
Path: "/reuse/{user}",
Summary: "Param re-use example",
}, func(ctx context.Context, input *struct {
// Example use as a path parameter.
ReusableParam
}) (*MyResponse, error) {
resp := &MyResponse{}
resp.Body.User = input.User
return resp, nil
})

// Tell the CLI how to start your router.
hooks.OnStart(func() {
http.ListenAndServe(fmt.Sprintf(":%d", options.Port), router)
})
})

// Run the CLI. When passed no commands, it starts the server.
cli.Run()
}
Loading