-
-
Save mymtw/4e5e8c425db96850bb10dd37c5411610 to your computer and use it in GitHub Desktop.
This file contains hidden or 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" | |
"encoding/json" | |
"fmt" | |
"github.com/hashicorp/go-retryablehttp" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"sync" | |
) | |
const ( | |
ProxyAddr = "127.0.0.1:9050" | |
) | |
func checkRetry(ctx context.Context, resp *http.Response, err error) (bool, error) { | |
return resp.StatusCode >= 403, err | |
} | |
func fetch(wg *sync.WaitGroup) { | |
// create a socks5 dialer | |
//dialer, err := proxy.SOCKS5("tcp", ProxyAddr, nil, proxy.Direct) | |
//dialContext := func(ctx context.Context, network, address string) (net.Conn, error) { | |
// return dialer.Dial(network, address) | |
//} | |
defer wg.Done() | |
transport := &http.Transport{ | |
//DialContext: dialContext, | |
DisableKeepAlives: true, | |
} | |
retryClient := retryablehttp.NewClient() | |
retryClient.RetryMax = 100 | |
retryClient.CheckRetry = checkRetry | |
retryClient.HTTPClient.Transport = transport | |
resp, err := retryClient.Get("http://127.0.0.1:8000/notify") | |
if err != nil { | |
log.Fatal(err) | |
return | |
} | |
body, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
fmt.Println("body read failed") | |
} | |
fmt.Println(string(body)) | |
} | |
type Server struct { | |
Counter int | |
} | |
func (s *Server) notify(rw http.ResponseWriter, req *http.Request) { | |
s.Counter++ | |
if s.Counter < 3 { | |
rw.WriteHeader(403) | |
return | |
} | |
rw.Header().Set("Content-Type", "application/json") | |
rw.WriteHeader(200) | |
resp := make(map[string]string) | |
resp["message"] = "Status Created" | |
jsonResp, err := json.Marshal(resp) | |
if err != nil { | |
log.Fatalf("Error happened in JSON marshal. Err: %s", err) | |
} | |
rw.Write(jsonResp) | |
} | |
func server() { | |
s := Server{Counter: 0} | |
http.HandleFunc("/notify", s.notify) | |
log.Fatal(http.ListenAndServe("127.0.0.1:8000", nil)) | |
} | |
func main() { | |
go server() | |
var wg sync.WaitGroup | |
for i := 0; i < 3; i++ { | |
wg.Add(1) | |
go func(wg *sync.WaitGroup) { | |
fetch(wg) | |
}(&wg) | |
} | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment