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).Methods("POST") 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)
}