55 "context"
66 "crypto/tls"
77 "fmt"
8+ "io"
89 "net"
910 "net/http"
1011 "strings"
@@ -15,6 +16,29 @@ import (
1516// It resolves to the specified address instead of using DNS.
1617// The status and body of the response is returned, or an error.
1718func Get (url , address string , timeout time.Duration ) (int , string , error ) {
19+ resp , err := makeRequest (http .MethodGet , url , address , nil , timeout )
20+ if err != nil {
21+ return 0 , "" , err
22+ }
23+
24+ defer resp .Body .Close ()
25+
26+ body := new (bytes.Buffer )
27+ _ , err = body .ReadFrom (resp .Body )
28+ if err != nil {
29+ return resp .StatusCode , "" , err
30+ }
31+
32+ return resp .StatusCode , body .String (), nil
33+ }
34+
35+ // Post sends a POST request to the specified url with the body as the payload.
36+ // It resolves to the specified address instead of using DNS.
37+ func Post (url , address string , body io.Reader , timeout time.Duration ) (* http.Response , error ) {
38+ return makeRequest (http .MethodPost , url , address , body , timeout )
39+ }
40+
41+ func makeRequest (method , url , address string , body io.Reader , timeout time.Duration ) (* http.Response , error ) {
1842 dialer := & net.Dialer {}
1943
2044 http .DefaultTransport .(* http.Transport ).DialContext = func (
@@ -30,9 +54,9 @@ func Get(url, address string, timeout time.Duration) (int, string, error) {
3054 ctx , cancel := context .WithTimeout (context .Background (), timeout )
3155 defer cancel ()
3256
33- req , err := http .NewRequestWithContext (ctx , http . MethodGet , url , nil )
57+ req , err := http .NewRequestWithContext (ctx , method , url , body )
3458 if err != nil {
35- return 0 , "" , err
59+ return nil , err
3660 }
3761
3862 var resp * http.Response
@@ -48,15 +72,8 @@ func Get(url, address string, timeout time.Duration) (int, string, error) {
4872 }
4973
5074 if err != nil {
51- return 0 , "" , err
52- }
53- defer resp .Body .Close ()
54-
55- body := new (bytes.Buffer )
56- _ , err = body .ReadFrom (resp .Body )
57- if err != nil {
58- return resp .StatusCode , "" , err
75+ return nil , err
5976 }
6077
61- return resp . StatusCode , body . String () , nil
78+ return resp , nil
6279}
0 commit comments