Skip to content

Instantly share code, notes, and snippets.

@anatolebeuzon
Last active October 15, 2019 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anatolebeuzon/f13965b0e8308397e313d6aca8da2d0b to your computer and use it in GitHub Desktop.
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`
{
"requestFrequencyInMS": 100,
"url": "http://localhost/",
"cookies": {
"key1": "value1",
"key2": "value2"
}
}
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