danielgtaylor / huma

Huma REST/HTTP API Framework for Golang with OpenAPI 3.1
https://huma.rocks/
MIT License
1.87k stars 138 forks source link

Required query parameter not going through validation when it is omitted #435

Closed camcalaquian closed 4 months ago

camcalaquian commented 4 months ago

Below slightly modified code from example. I was assuming that by default an input is a required parameter based from the documentation.

package main

import (
    "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. Pass `--port` or set the `SERVICE_PORT` env var.
type Options struct {
    Port int `help:"Port to listen on" short:"p" default:"8888"`
}

// GreetingOutput represents the greeting operation response.
type GreetingOutput struct {
    Body struct {
        Message string `json:"message" example:"Hello, world!" doc:"Greeting message" nullable:"false"`
    }
}

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

        // Add the operation handler to the API.
        huma.Get(api, "/greeting", func(ctx context.Context, input *struct {
            Name string `query:"name" maxLength:"30" example:"world" doc:"Name to greet"`
        }) (*GreetingOutput, error) {
            resp := &GreetingOutput{}
            resp.Body.Message = fmt.Sprintf("Hello, %s!", input.Name)
            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()
}

When I run the above code go to http://localhost:8888/greeting I am not getting validation error for some reason. I just prints out

{
    "$schema": "http://localhost:8888/schemas/GreetingOutputBody.json",
    "message": "Hello, !"
}
camcalaquian commented 4 months ago

Closing as this is not an issue. I need to specify required:"true" for query parameters