Created
April 19, 2019 06:45
-
-
Save wirepair/920a685f5880849274e656876c0a6a83 to your computer and use it in GitHub Desktop.
http client ban ip on request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"crypto/tls" | |
"errors" | |
"log" | |
"net" | |
"net/http" | |
"net/http/httputil" | |
"time" | |
) | |
func IsBannedIP(ip string) bool { | |
if ip == "93.184.216.34" { | |
return true | |
} | |
return false | |
} | |
func main() { | |
timeout := 10 * time.Second | |
tr := &http.Transport{ | |
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { | |
c, err := net.Dial(network, addr) | |
if err != nil { | |
return nil, err | |
} | |
ip, _, _ := net.SplitHostPort(c.RemoteAddr().String()) | |
if IsBannedIP(ip) { | |
log.Printf("BANNED IP") | |
return nil, errors.New("ip address is banned") | |
} | |
return c, err | |
}, | |
DialTLS: func(network, addr string) (net.Conn, error) { | |
c, err := tls.Dial(network, addr, &tls.Config{InsecureSkipVerify: true}) | |
if err != nil { | |
return nil, err | |
} | |
ip, _, _ := net.SplitHostPort(c.RemoteAddr().String()) | |
if IsBannedIP(ip) { | |
log.Printf("TLS BANNED IP") | |
return nil, errors.New("ip address is banned") | |
} | |
err = c.Handshake() | |
if err != nil { | |
return c, err | |
} | |
return c, c.Handshake() | |
}, | |
TLSClientConfig: &tls.Config{ | |
InsecureSkipVerify: true, | |
}, | |
TLSHandshakeTimeout: 5 * time.Second, | |
MaxIdleConns: 0, | |
MaxIdleConnsPerHost: 10, | |
MaxConnsPerHost: 0, | |
ResponseHeaderTimeout: timeout, | |
ExpectContinueTimeout: timeout, | |
} | |
c := &http.Client{ | |
Transport: tr, | |
Timeout: timeout, | |
} | |
resp, err := c.Get("https://example.com:443/") | |
if err != nil { | |
log.Printf("nopers: %v", err) | |
return | |
} | |
defer resp.Body.Close() | |
// we shouldn't get here | |
data, err := httputil.DumpResponse(resp, true) | |
if err != nil { | |
log.Printf("error dumping response: %v\n", err) | |
} | |
log.Printf("response: %s\n", string(data)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment