|
No exemplo anterior foi apresentado como configurar um simples
servidor HTTP. Os servidores HTTP são úteis para
demonstrar o uso de |
![]()
package main |
import ( "fmt" "net/http" "time" ) |
|
func hello(w http.ResponseWriter, req *http.Request) { |
|
|
Um |
ctx := req.Context()
fmt.Println("server: hello handler started")
defer fmt.Println("server: hello handler ended")
|
|
Aguarda alguns segundos antes de enviar a resposta
para o cliente, para simular algum trabalho que o
servidor possa fazer. Enquanto trabalha, acompanha
o canal |
select {
case <-time.After(10 * time.Second):
fmt.Fprintf(w, "hello\n")
case <-ctx.Done():
|
|
O método |
err := ctx.Err()
fmt.Println("server:", err)
internalError := http.StatusInternalServerError
http.Error(w, err.Error(), internalError)
}
}
|
func main() { |
|
|
Como antes, o handler é registrado na rota “/hello” e o servidor é iniciado em seguida. |
http.HandleFunc("/hello", hello)
http.ListenAndServe(":8090", nil)
}
|
|
Executa o servidor em background. |
$ go run context-in-http-servers.go &
|
|
Simula uma requisição de cliente para |
$ curl localhost:8090/hello server: hello handler started ^C server: context canceled server: hello handler ended |
Próximo exemplo: Spawning Processes.