From 13a4fe1c044a49d1c9962694979c058364795b32 Mon Sep 17 00:00:00 2001 From: Kalle Carlbark Date: Tue, 20 Aug 2024 11:09:55 +0200 Subject: [PATCH] first commit --- .gitignore | 1 + README.md | 8 ++++++++ go.mod | 3 +++ main.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 62 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 go.mod create mode 100644 main.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e03b4a6 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +sw diff --git a/README.md b/README.md new file mode 100644 index 0000000..765b647 --- /dev/null +++ b/README.md @@ -0,0 +1,8 @@ +# sw - Simple Web Server +Listen on a specified port and prints out client information such as +- Client IP address +- Client source port +- Client headers +- Client body if sent + +Useful for debugging http requests with for example ngrok. \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..5955331 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module sw + +go 1.19 diff --git a/main.go b/main.go new file mode 100644 index 0000000..2a12cbc --- /dev/null +++ b/main.go @@ -0,0 +1,50 @@ +package main + +import ( + "flag" + "fmt" + "io" + "net/http" + "time" +) + +var port = flag.String("port", "3000", "listen on port") +var body = flag.Bool("body", true, "print body") +var header = flag.Bool("header", true, "print headers") + +func requestHandler(w http.ResponseWriter, r *http.Request) { + fmt.Printf("%s %s from %s", r.Method, r.RequestURI, r.RemoteAddr) + + if *body { + r.Body = http.MaxBytesReader(w, r.Body, 1048576) + body, err := io.ReadAll(r.Body) + if err != nil { + http.Error(w, "unable to read response", http.StatusBadRequest) + } + fmt.Printf("\n--- BODY ---\n%s\n", string(body)) + } + + if *header { + fmt.Println(r.Header) + } + + fmt.Fprintf(w, "The current time is: %s\n", time.Now()) +} + +func main() { + flag.Parse() + + srv := http.Server{ + Addr: ":" + *port, + WriteTimeout: 10 * time.Second, + ReadHeaderTimeout: 10 * time.Second, + Handler: http.HandlerFunc(requestHandler), + } + + fmt.Printf("Starting server on port %s\n", *port) + //srv.HandleFunc("/", requestHandler) + err := srv.ListenAndServe() + if err != nil { + fmt.Println("ListenAndServe:", err) + } +}