From 1d3369137aaa5ff301822c1c885ed7facfd412ba Mon Sep 17 00:00:00 2001 From: Emile Date: Wed, 10 Jun 2020 15:23:50 +0200 Subject: Initial commit --- main.go | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 main.go (limited to 'main.go') diff --git a/main.go b/main.go new file mode 100644 index 0000000..fcd69a8 --- /dev/null +++ b/main.go @@ -0,0 +1,74 @@ +package main + +import ( + "bytes" + "fmt" + "io/ioutil" + "net" + "net/http" + + "github.com/gorilla/mux" + "github.com/sirupsen/logrus" +) + +var requests []*http.Request + +func main() { + + // define the host and port on which the server should be listening on + host := "0.0.0.0" + port := "8085" + + // defin the gorilla/mux router with a pathprefix on / routing all requests + // to the indexHandler function + r := mux.NewRouter() + r.HandleFunc("/resetall", resetHandler) + r.PathPrefix("/").HandlerFunc(indexHandler) + + // define and start the http server + httpServer := http.Server{ + Addr: net.JoinHostPort(host, port), + Handler: r, + } + logrus.Fatal(httpServer.ListenAndServe()) +} + +// indexhandler handles requests to the /.* endpoints logging the results +func indexHandler(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(w, "%s\n\n", "request logger") + fmt.Fprintf(w, "%s\n", "
")
+	fmt.Fprintf(w, "%s\n\n", "method\tlen\tURI\tbody")
+
+	// if the request path is not "/", append the request to the list of requests
+	if r.RequestURI != "/" {
+		requests = append(requests, r)
+	}
+
+	// write some elements to the responseWriter
+	for _, element := range requests {
+		fmt.Fprintf(w, "%s\t", element.Method)
+		fmt.Fprintf(w, "%d\t", element.ContentLength)
+		fmt.Fprintf(w, "%v\t", element.RequestURI)
+
+		// read the request body
+		defer element.Body.Close()
+		body, err := ioutil.ReadAll(element.Body)
+		if err != nil {
+			fmt.Fprintf(w, "%s: %s\n", "no body to be read", err)
+			continue
+		}
+
+		// set the body as the element body, this makes it possible to use it
+		// again in the next requests
+		element.Body = ioutil.NopCloser(bytes.NewBuffer(body))
+		fmt.Fprintf(w, "%s\n", string(body))
+	}
+	fmt.Fprintf(w, "%s\n", "
") +} + +// resetHandler handles requests to the /resetall endpoint clearing the reqeusts +// slice +func resetHandler(w http.ResponseWriter, r *http.Request) { + requests = []*http.Request{} + http.Redirect(w, r, "/", http.StatusSeeOther) +} -- cgit 1.4.1