first commit

This commit is contained in:
Kalle Carlbark 2024-08-20 11:09:55 +02:00
commit 13a4fe1c04
No known key found for this signature in database
4 changed files with 62 additions and 0 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
sw

8
README.md Normal file
View file

@ -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.

3
go.mod Normal file
View file

@ -0,0 +1,3 @@
module sw
go 1.19

50
main.go Normal file
View file

@ -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)
}
}