about summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--README.md1
-rw-r--r--main.go74
2 files changed, 75 insertions, 0 deletions
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..e362e06
--- /dev/null
+++ b/README.md
@@ -0,0 +1 @@
+# reqlog is a simple http server logging the requests made to the server
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", "<b>request logger</b>")
+	fmt.Fprintf(w, "%s\n", "<pre>")
+	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", "</pre>")
+}
+
+// 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)
+}