github.com/gbl08ma/monkey@v1.1.0/examples/no_http.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"reflect"
     7  	"strings"
     8  
     9  	"github.com/gbl08ma/monkey"
    10  )
    11  
    12  func main() {
    13  	var guard *monkey.PatchGuard
    14  	guard = monkey.PatchInstanceMethod(reflect.TypeOf(http.DefaultClient), "Get", func(c *http.Client, url string) (*http.Response, error) {
    15  		guard.Unpatch()
    16  		defer guard.Restore()
    17  
    18  		if !strings.HasPrefix(url, "https://") {
    19  			return nil, fmt.Errorf("only https requests allowed")
    20  		}
    21  
    22  		return c.Get(url)
    23  	})
    24  
    25  	_, err := http.Get("http://google.com")
    26  	fmt.Println(err) // only https requests allowed
    27  	resp, err := http.Get("https://google.com")
    28  	fmt.Println(resp.Status, err) // 200 OK <nil>
    29  }