Created
October 9, 2023 07:22
-
-
Save cathyxz/712aa707b56bb18735be6e039ae6b921 to your computer and use it in GitHub Desktop.
A hacky go script used to verify the keepalive idle timeout for websites. Used for verifying that nginx keepalive_timeout configuration is working as intended.
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 ( | |
"bufio" | |
"errors" | |
"fmt" | |
"io" | |
"net" | |
"syscall" | |
"time" | |
) | |
func establishTCPConnection(address string) (net.Conn, error) { | |
tcpAddr, err := net.ResolveTCPAddr("tcp", address) | |
if err != nil { | |
fmt.Printf("Failed to resolve TCP address: %v", err) | |
return nil, err | |
} | |
conn, err := net.DialTCP("tcp", nil, tcpAddr) | |
if err != nil { | |
fmt.Printf("Failed to connect to server: %v", err) | |
return conn, err | |
} | |
return conn, nil | |
} | |
func readResponse(r *bufio.Reader) error { | |
httpStatus, err := r.ReadString('\n') | |
if err != nil { | |
if errors.Is(err, syscall.ECONNRESET) { | |
fmt.Printf("Connection was reset by the server: %v \n", err) | |
return err | |
} | |
if errors.Is(err, io.EOF) { | |
fmt.Printf("Nothing to read: %v \n", err) | |
return err | |
} | |
fmt.Printf("Unexpected error: %v", err) | |
return err | |
} | |
fmt.Print(httpStatus) | |
bytesRemaining := r.Buffered() | |
fmt.Printf("Bytes available: %d\n", bytesRemaining) | |
return nil | |
} | |
func isAliveAfter(address string, d time.Duration) bool { | |
conn, err := establishTCPConnection(address) | |
if err != nil { | |
fmt.Print(err) | |
return false | |
} | |
defer conn.Close() | |
reader := bufio.NewReader(conn) | |
fmt.Fprintf(conn, "GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n") | |
err = readResponse(reader) | |
if err != nil { | |
fmt.Printf("Reading response to initial request failed: %v", err) | |
return false | |
} | |
fmt.Printf("Waiting %ds\n", int(d.Seconds())) | |
time.Sleep(d) | |
if err != nil { | |
fmt.Printf("Reading response to second request failed: %v", err) | |
return false | |
} | |
return true | |
} | |
func main() { | |
n := 59 * time.Second | |
address := "localhost:80" | |
for isAliveAfter(address, n) { | |
if n > 350*time.Second { | |
break | |
} | |
n += 2 * time.Second | |
} | |
fmt.Printf("Keepalive for %s is shorter than %d seconds.\n", address, int(n.Seconds())) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment