Context
This program is a simple HTTP server written in Go that defines an HTTP handler function called hello
. This handler uses the request's context to implement a timeout for processing the request.
Here's a breakdown of the code:
Explanation:
hello
is an HTTP handler function that uses the request's context (ctx
). It prints messages when the handler starts and ends.Inside the
select
statement, there are two cases:If the operation (responding with "hello\n") completes within 10 seconds, the response is sent.
If the context is canceled (due to a timeout or cancellation), an error message is printed, and an internal server error response is sent.
In the
main
function:The
/hello
path is registered with thehello
handler usinghttp.HandleFunc
.The server is started using
http.ListenAndServe
on port8090
.
This program demonstrates a simple way to handle timeouts in an HTTP server using the request context.
Last updated
Was this helpful?