Snippets

Patrick Logan Cancel An HTTP Request With Go's net/http Package

Created by Patrick Logan
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

func main() {
	cancel := make(chan struct{})
	req, err := http.NewRequest("GET", "http://fake-response.appspot.com/?sleep=20", nil)
	if err != nil {
		log.Fatal(err)
	}
	req.Cancel = cancel
	go func() {
		c := &http.Client{}
		res, err := c.Do(req)
		if err != nil {
			log.Fatal(err)
		}
		page, err := ioutil.ReadAll(res.Body)
		res.Body.Close()
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%s", page)
	}()

	go func() {
		time.Sleep(5 * time.Second)
		cancel <- struct{}{}
	}()
	time.Sleep(60 * time.Second)
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.