packagemainimport("context""fmt""net/http""github.com/danielgtaylor/huma/v2""github.com/danielgtaylor/huma/v2/adapters/humachi""github.com/danielgtaylor/huma/v2/humacli""github.com/go-chi/chi/v5"_"github.com/danielgtaylor/huma/v2/formats/cbor")// Options for the CLI.typeOptionsstruct{Portint`help:"Port to listen on" short:"p" default:"8888"`}// GreetingOutput represents the greeting operation response.typeGreetingOutputstruct{Bodystruct{Messagestring`json:"message" example:"Hello, world!" doc:"Greeting message"`}}// ReviewInput represents the review operation request.typeReviewInputstruct{Bodystruct{Authorstring`json:"author" maxLength:"10" doc:"Author of the review"`Ratingint`json:"rating" minimum:"1" maximum:"5" doc:"Rating from 1 to 5"`Messagestring`json:"message,omitempty" maxLength:"100" doc:"Review message"`}}funcmain(){// Create a CLI app which takes a port option.cli:=humacli.New(func(hookshumacli.Hooks,options*Options){// Create a new router & APIrouter:=chi.NewMux()api:=humachi.New(router,huma.DefaultConfig("My API","1.0.0"))// Register GET /greeting/{name}huma.Register(api,huma.Operation{OperationID:"get-greeting",Method:http.MethodGet,Path:"/greeting/{name}",Summary:"Get a greeting",Description:"Get a greeting for a person by name.",Tags:[]string{"Greetings"},},func(ctxcontext.Context,input*struct{Namestring`path:"name" maxLength:"30" example:"world" doc:"Name to greet"`})(*GreetingOutput,error){resp:=&GreetingOutput{}resp.Body.Message=fmt.Sprintf("Hello, %s!",input.Name)returnresp,nil})// Register POST /reviewshuma.Register(api,huma.Operation{OperationID:"post-review",Method:http.MethodPost,Path:"/reviews",Summary:"Post a review",Tags:[]string{"Reviews"},DefaultStatus:http.StatusCreated,},func(ctxcontext.Context,i*ReviewInput)(*struct{},error){// TODO: save review in data store.returnnil,nil})// Tell the CLI how to start your server.hooks.OnStart(func(){fmt.Printf("Starting server on port %d...\n",options.Port)http.ListenAndServe(fmt.Sprintf(":%d",options.Port),router)})})// Run the CLI. When passed no commands, it starts the server.cli.Run()}
You can also try sending invalid data, and see how you get exhaustive errors back from your API. Omit the author body field and use a rating outside the range of valid values: