A simple request logger
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
1.9 KiB

package main
import (
var requests []*http.Request
func main() {
// define the host and port on which the server should be listening on
host := ""
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")
// define and start the http server
httpServer := http.Server{
Addr: net.JoinHostPort(host, port),
Handler: r,
// 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)
// 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)