Created
December 1, 2021 18:53
-
-
Save mlh758/0b1b86efe6f67ba5ad0d4fcab049b3b7 to your computer and use it in GitHub Desktop.
Simulate slow HTTP server.
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 ( | |
"flag" | |
"fmt" | |
"log" | |
"math/rand" | |
"net" | |
"os" | |
"strings" | |
"time" | |
) | |
const DEFAULT_BODY = `HTTP/1.1 %s OK | |
X-elastic-product: Fake Elasticsearch | |
content-type: application/json; charset=UTF-8 | |
content-length: 21 | |
{"acknowledged":true}` | |
const ( | |
CONN_HOST = "localhost" | |
CONN_TYPE = "tcp" | |
) | |
var port = flag.Uint("port", 9200, "port to listen on") | |
var responseDelay = flag.Int("responseDelay", 10, "how many seconds to wait before responding") | |
var statusCodes = flag.String("statuses", "200", "comma separated list of HTTP response codes to potentially reply with") | |
// hit this server with curl -X POST --data "whatever" --connect-timeout 1 http://localhost:9200 | |
func main() { | |
flag.Parse() | |
address := fmt.Sprint(CONN_HOST, ":", *port) | |
statuses := strings.Split(*statusCodes, ",") | |
l, err := net.Listen(CONN_TYPE, address) | |
if err != nil { | |
log.Println("Error listening:", err.Error()) | |
os.Exit(1) | |
} | |
defer l.Close() | |
log.Println("Listening on " + address) | |
for { | |
// Listen for an incoming connection. | |
conn, err := l.Accept() | |
if err != nil { | |
log.Println("Error accepting: ", err.Error()) | |
os.Exit(1) | |
} | |
// Actually serve the request | |
status := statuses[rand.Intn(len(statuses))] | |
go handleRequest(conn, status) | |
} | |
} | |
// Handles incoming requests. | |
func handleRequest(conn net.Conn, status string) { | |
reqID := rand.Int63() | |
log.Printf("Received request %d", reqID) | |
buf := make([]byte, 1024) | |
_, err := conn.Read(buf) | |
if err != nil { | |
log.Println("Error reading:", err.Error()) | |
} | |
// Delay a response | |
time.Sleep(time.Duration(*responseDelay) * time.Second) | |
conn.Write([]byte(fmt.Sprintf(DEFAULT_BODY, status))) | |
conn.Close() | |
log.Printf("Sent %s response for %d", status, reqID) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment