Last active
October 15, 2019 12:01
-
-
Save anatolebeuzon/f13965b0e8308397e313d6aca8da2d0b to your computer and use it in GitHub Desktop.
Do a POST request every n milliseconds. Supports concurrent in-flight requests. Usage: `go run main.go`
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
{ | |
"requestFrequencyInMS": 100, | |
"url": "http://localhost/", | |
"cookies": { | |
"key1": "value1", | |
"key2": "value2" | |
} | |
} |
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 ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"time" | |
) | |
const configFile = "config.json" | |
type config struct { | |
RequestFrequencyInMS int | |
URL string | |
Cookies map[string]string | |
} | |
func main() { | |
file, err := ioutil.ReadFile(configFile) | |
if err != nil { | |
log.Fatal("failed to open config file: ", err) | |
} | |
c := &config{} | |
err = json.Unmarshal([]byte(file), &c) | |
if err != nil { | |
log.Fatal("failed to unmarshal config file: ", err) | |
} | |
logger := make(chan string, 100) | |
req, err := http.NewRequest("POST", c.URL, nil) | |
if err != nil { | |
log.Fatal("failed to create request: ", err) | |
} | |
for k, v := range c.Cookies { | |
req.AddCookie(&http.Cookie{Name: k, Value: v}) | |
} | |
for { | |
select { | |
case <-time.Tick(time.Duration(c.RequestFrequencyInMS) * time.Millisecond): | |
go doRequest(req, logger) | |
case msg := <-logger: | |
log.Println(msg) | |
} | |
} | |
} | |
func doRequest(req *http.Request, logger chan string) { | |
resp, err := http.DefaultClient.Do(req) | |
if err != nil { | |
logger <- fmt.Sprintf("request failed: %s", err) | |
return | |
} | |
defer resp.Body.Close() | |
logger <- resp.Status | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment