sw/main.go

57 lines
1.3 KiB
Go

package main
import (
"compress/gzip"
"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 {
var requestbody []byte
r.Body = http.MaxBytesReader(w, r.Body, 1048576)
if r.Header.Get("Content-Encoding") == "gzip" {
gzipreader, _ := gzip.NewReader(r.Body)
requestbody, _ = io.ReadAll(gzipreader)
}
requestbody, 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(requestbody))
}
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)
}
}