Go by Example: Context

package main

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

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	req, err := http.NewRequestWithContext(ctx, "GET", "https://www.google.com", nil)
	if err != nil {
		fmt.Println(err)
		return
	}

	client := &http.Client{}
	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(res.Status)
}

This example shows how to use the context package to enforce a timeout on an HTTP request. The context.WithTimeout function is used to create a context that is cancelled after the specified timeout of one second. The http.NewRequestWithContext function is used to create an HTTP request with the specified context. The request is sent using an http.Client and the response status code is printed. If the request takes longer than one second, the context will be cancelled and the request will be terminated, resulting in an error.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *