sw/main.go

56 lines
1.2 KiB
Go
Raw Permalink Normal View History

2024-08-20 11:09:55 +02:00
package main
import (
2024-08-20 13:38:20 +02:00
"compress/gzip"
2024-08-20 11:09:55 +02:00
"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 {
2024-08-20 13:38:20 +02:00
var requestbody []byte
2024-08-20 11:09:55 +02:00
r.Body = http.MaxBytesReader(w, r.Body, 1048576)
2024-08-20 13:38:20 +02:00
if r.Header.Get("Content-Encoding") == "gzip" {
gzipreader, _ := gzip.NewReader(r.Body)
requestbody, _ = io.ReadAll(gzipreader)
2024-08-20 13:40:51 +02:00
} else {
requestbody, _ = io.ReadAll(r.Body)
2024-08-20 11:09:55 +02:00
}
2024-08-20 13:41:46 +02:00
fmt.Printf("\n--- BODY ---\n%s\n--- ENDBODY ---\n", string(requestbody))
2024-08-20 11:09:55 +02:00
}
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)
}
}