context

context

原文:https://gobyexample.com/context

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Note:
// This code is from https://gobyexample.com.
package main

import (
	"fmt"
	"net/http"
	"time"
)

func hello(w http.ResponseWriter, req *http.Request) {
	ctx := req.Context()
	fmt.Println("server: hello handler started")
	defer fmt.Println("server: hello handler ended")

	select {
	case <-time.After(10 * time.Second):
		fmt.Fprintf(w, "hello\n")
	case <-ctx.Done():
		err := ctx.Err()
		fmt.Println("server:", err)
		internalError := http.StatusInternalServerError
		http.Error(w, err.Error(), internalError)
	}
}

func main() {
	http.HandleFunc("/hello", hello)
	http.ListenAndServe(":8090", nil)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
PS D:\Dev\Go\byExample\context> go run main.go
server: hello handler started
server: hello handler ended
server: hello handler started
server: hello handler ended
server: hello handler started
server: context canceled <- 按了 CTRL +C
server: hello handler ended
server: hello handler started
server: context canceled <- 按了 CTRL +C
server: hello handler ended
server: hello handler started
server: hello handler ended
server: hello handler started
server: hello handler ended
server: hello handler started
server: context canceled <- 按了 CTRL +C
server: hello handler ended
最后修改 October 10, 2024: 更新 (a4b8f85)