golang context

好风 发表于 2018-11-01T06:14:29.365275Z
引用地址:https://plus.ooclab.com/note/article/1426

context 有很多用途,现在已经提升至标准库

取消操作

package main

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

func main() {
    // Create an HTTP server that listens on port 8000
    http.ListenAndServe(":8000", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        ctx := r.Context()
        // This prints to STDOUT to show that processing has started
        fmt.Fprint(os.Stdout, "processing request\n")
        // We use `select` to execute a peice of code depending on which
        // channel receives a message first
        select {
        case <-time.After(2 * time.Second):
            // If we receive a message after 2 seconds
            // that means the request has been processed
            // We then write this as the response
            w.Write([]byte("request processed"))
        case <-ctx.Done():
            // If the request gets cancelled, log it
            // to STDERR
            fmt.Fprint(os.Stderr, "request cancelled\n")
        }
    }))
}

运行上面程序,在浏览器打开 http://127.0.0.1:8000 端口,如果2秒之内关闭浏览器,就能在程序日志中看到 request cancelled 消息。