zoukankan      html  css  js  c++  java
  • go官方的http.request + context样例

    go官方的http.request + context样例

    https://github.com/DavadDi/go_study/blob/master/src/httpreq_context/main.go

    package main
    
    import (
    	"context"
    	"fmt"
    	"io/ioutil"
    	"log"
    	"net/http"
    	"time"
    )
    
    func HttpDoTest(ctx context.Context, resChan chan<- string) error {
    	start := time.Now()
    
    	repoUrl := "https://api.github.com/repos/campoy/golang-plugins"
    	req, err := http.NewRequest("GET", repoUrl, nil)
    	if err != nil {
    		return fmt.Errorf("http.NewRequest Error: %s", err.Error())
    	}
    
    	// in go >= 1.7
    	req = req.WithContext(ctx)
    
    	client := &http.Client{}
    	resp, err := client.Do(req)
    	if err != nil {
    		return fmt.Errorf("client.Do Error: %s", err.Error())
    	}
    
    	data, err := ioutil.ReadAll(resp.Body)
    	if err != nil {
    		return fmt.Errorf("ioutil.ReadAll Error: %s", err.Error())
    	}
    
    	log.Printf("Read body size [%d]", len(data))
    	log.Println("CostTime is: " + time.Since(start).String())
    
    	resChan <- string(data)
    
    	return nil
    }
    
    func main() {
    	deadline := 1
    	d := time.Now().Add(time.Duration(deadline) * time.Second) // deadline max
    	ctx, cancel := context.WithDeadline(context.Background(), d)
    	defer cancel()
    
    	resChan := make(chan string)
    
    	go HttpDoTest(ctx, resChan)
    
    	var resData string
    	select {
    	case <-ctx.Done():
    		fmt.Println(ctx.Err())
    
    		/* just for ex use. No used*/
    	case <-time.Tick(time.Duration(time.Duration(deadline*2) * time.Second)):
    		fmt.Println("Time over!")
    
    	case resData = <-resChan:
    		fmt.Println("Read data finished")
    	}
    
    	log.Printf("Read data size: [%d]", len(resData))
    }
    

      

  • 相关阅读:
    2019年下半年学习总结
    要看的积累
    【长期积累】Java
    【长期积累】数据库
    一些知识总结
    一些小总结
    优秀前端框架Semantic UI
    windows nodejs express的安装
    形象的讲解angular中的$q与promise(转)
    centos6.5 install mongodb
  • 原文地址:https://www.cnblogs.com/shhnwangjian/p/9024919.html
Copyright © 2011-2022 走看看