huma/examples/timeout/timeout.go

43 lines
1.1 KiB
Go
Raw Permalink Normal View History

2020-04-05 14:10:09 -07:00
package main
import (
"context"
"net/http"
"time"
"github.com/danielgtaylor/huma"
2020-08-26 22:25:47 -07:00
"github.com/danielgtaylor/huma/cli"
"github.com/danielgtaylor/huma/responses"
2020-04-05 14:10:09 -07:00
)
func main() {
2020-08-26 22:25:47 -07:00
app := cli.NewRouter("Timeout Example", "1.0.0")
2020-04-05 14:10:09 -07:00
2020-08-26 22:25:47 -07:00
app.Resource("/timeout").Get("timeout", "Timeout example",
responses.String(http.StatusOK),
responses.InternalServerError(),
).Run(func(ctx huma.Context) {
2020-08-27 10:15:33 -07:00
// Add a timeout to the context. No outgoing request should take longer
// than 2 seconds or we abort.
2020-04-05 14:10:09 -07:00
newCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
// Create a new request that will take 5 seconds to complete.
req, _ := http.NewRequestWithContext(
newCtx, http.MethodGet, "https://httpstat.us/418?sleep=5000", nil)
// Make the request. This will return with an error because the context
// deadline of 2 seconds is shorter than the request duration of 5 seconds.
_, err := http.DefaultClient.Do(req)
if err != nil {
2020-08-26 22:25:47 -07:00
ctx.WriteError(http.StatusInternalServerError, "Problem with HTTP request", err)
return
2020-04-05 14:10:09 -07:00
}
2020-08-27 10:15:33 -07:00
// Success case, which we never get to.
2020-08-26 22:25:47 -07:00
ctx.Write([]byte("success!"))
2020-04-05 14:10:09 -07:00
})
2020-08-26 22:25:47 -07:00
app.Run()
2020-04-05 14:10:09 -07:00
}