1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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).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", "<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)
}
|