0148-Go-上下文

环境

  • Time 2022-08-25
  • Go 1.19

前言

说明

参考:https://gobyexample.com/context

目标

使用 Go 语言的上下文。

示例

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)
}

总结

使用 Go 语言的上下文。

附录

posted @ 2023-01-30 19:10  波尔  阅读(14)  评论(0编辑  收藏  举报