ctx控制超时的使用

cancel
package main

import (
    "context"
    "fmt"
    "time"
)

func gen(ctx context.Context) <-chan int {
    dst := make(chan int)
    n := 1
    go func() {
        for {
            select {
            case <-ctx.Done():
                fmt.Println("i exited")
                return // returning not to leak the goroutine
            case dst <- n:
                n++
            }
        }
    }()
    return dst
}

func test() {
    // gen generates integers in a separate goroutine and
    // sends them to the returned channel.
    // The callers of gen need to cancel the context once
    // they are done consuming generated integers not to leak
    // the internal goroutine started by gen.
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel() // cancel when we are finished consuming integers
    intChan := gen(ctx)
    for n := range intChan {
        fmt.Println(n)
        if n == 5 {
            break
        }
    }
}
func main() {
    test()
    time.Sleep(time.Hour)
}
deadline
package main

import (
    "context"
    "fmt"
    "time"
)

func main() {
    d := time.Now().Add(1000 * time.Millisecond)
    ctx, cancel := context.WithDeadline(context.Background(), d)

    // Even though ctx will be expired, it is good practice to call its
    // cancelation function in any case. Failure to do so may keep the
    // context and its parent alive longer than necessary.
    defer cancel()

    select {
    case <-time.After(1 * time.Second):
        fmt.Println("overslept")
    case <-ctx.Done():
        fmt.Println(ctx.Err())
    }

}
timeout
package main

import (
    "context"
    "fmt"
    "io/ioutil"
    "net/http"
    "time"
)
type Result struct {
    r   *http.Response
    err error
}
func process() {
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
    defer cancel()
    tr := &http.Transport{}
    client := &http.Client{Transport: tr}
    c := make(chan Result, 1)
    req, err := http.NewRequest("GET", "http://www.baidu.com", nil)
    if err != nil {
        fmt.Println("http request failed, err:", err)
        return
    }
    go func() {
        resp, err := client.Do(req)
        pack := Result{r: resp, err: err}
        c <- pack
    }()
    select {
    case <-ctx.Done():
        tr.CancelRequest(req)
        res := <-c
        fmt.Println("Timeout! err:", res.err)
    case res := <-c:
        defer res.r.Body.Close()
        out, _ := ioutil.ReadAll(res.r.Body)
        fmt.Printf("Server Response: %s", out)
    }
    return
}
func main() {
    process()
}

value

package main

import (
    "context"
    "fmt"
)

func process(ctx context.Context) {
    ret,ok := ctx.Value("trace_id").(int)
    if !ok {
        ret = 21342423
    }

    fmt.Printf("ret:%d\n", ret)

    s , _ := ctx.Value("session").(string)
    fmt.Printf("session:%s\n", s)
}

func main() {
    ctx := context.WithValue(context.Background(), "trace_id", 13483434)
    ctx = context.WithValue(ctx, "session", "sdlkfjkaslfsalfsafjalskfj")
    process(ctx)
}




posted @ 2019-12-19 19:27  离地最远的星  阅读(472)  评论(0编辑  收藏  举报