Skip to content

Instantly share code, notes, and snippets.

@danielgtaylor
Created December 14, 2023 05:52
Show Gist options
  • Save danielgtaylor/3f6b0cdb3f88ccf74fcef4773341c7ba to your computer and use it in GitHub Desktop.
Save danielgtaylor/3f6b0cdb3f88ccf74fcef4773341c7ba to your computer and use it in GitHub Desktop.
Huma v2 manual doc
package main
import (
"encoding/json"
"fmt"
"net/http"
"reflect"
"github.com/danielgtaylor/huma/v2"
"github.com/go-chi/chi/v5"
"github.com/goccy/go-yaml"
)
func Addr[T any](value T) *T {
return &value
}
type GreetingOutput struct {
Message string `json:"message"`
}
func main() {
// Create the schema registry which will hold schemas that refs can point to.
registry := huma.NewMapRegistry("#/components/schemas/", huma.DefaultSchemaNamer)
// Create the OpenAPI document.
doc := huma.OpenAPI{
OpenAPI: "3.1.0",
Info: &huma.Info{
Title: "My API",
Version: "1.0.0",
},
Components: &huma.Components{
Schemas: registry,
},
Paths: map[string]*huma.PathItem{},
}
// Create a new router.
router := chi.NewMux()
// Manually document the route in the OpenAPI.
doc.Paths["/greeting/{name}"] = &huma.PathItem{
Get: &huma.Operation{
OperationID: "get-greeting",
Summary: "Get a greeting",
Parameters: []*huma.Param{
&huma.Param{
Name: "name",
In: "path",
Required: true,
Schema: &huma.Schema{
Type: "string",
MaxLength: Addr(30),
Examples: []any{"world"},
Description: "Name to greet",
Extensions: map[string]interface{}{
"x-my-custom-extension": "some value",
},
},
},
},
Responses: map[string]*huma.Response{
"200": &huma.Response{
Description: "Greeting message",
Content: map[string]*huma.MediaType{
"application/json": &huma.MediaType{
Schema: registry.Schema(reflect.TypeOf(GreetingOutput{}), true, ""),
},
},
},
},
},
}
router.Get("/greeting/{name}", func(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "name")
resp := &GreetingOutput{}
resp.Message = fmt.Sprintf("Hello, %s!", name)
b, _ := json.Marshal(resp)
w.Header().Set("Content-Type", "application/json")
w.Write(b)
})
// ...
// Dump the OpenAPI
b, _ := yaml.Marshal(doc)
fmt.Println(string(b))
// Start the server
http.ListenAndServe("127.0.0.1:8000", router)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment