-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpsink.go
More file actions
58 lines (51 loc) · 1.44 KB
/
httpsink.go
File metadata and controls
58 lines (51 loc) · 1.44 KB
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
package main
import (
"flag"
"fmt"
"log"
"net/http"
"net/http/httptest"
"net/http/httputil"
"time"
)
func main() {
addr := flag.String("addr", ":19091", "HTTP network address")
sleep := flag.Duration("sleep", 0, "sleeptime for non proxy function")
flag.Parse()
http.HandleFunc("/", rootHandler(*sleep))
log.Printf("Starting server on %s\n", *addr)
err := http.ListenAndServe(*addr, logRequest(http.DefaultServeMux))
if err != nil {
log.Fatalln(err)
}
}
func rootHandler(sleep time.Duration) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
time.Sleep(sleep)
_, _ = fmt.Fprintf(w, "")
}
}
func logRequest(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
x, err := httputil.DumpRequest(r, true)
//defer func() {
// _ = r.Body.Close()
//}()
//body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
return
}
//log.Printf("%s %s\n", err, string(body))
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, r)
message := fmt.Sprintf("Time:%v\nUrl:\n%sRequest:\n%s\nResponse Code: %d\nResponse:\n%s\n\n", time.Now(), r.URL.Path, string(x), rec.Code, rec.Body.String())
fmt.Println(message)
// this copies the recorded response to the response writer
for k, v := range rec.Header() {
w.Header()[k] = v
}
w.WriteHeader(rec.Code)
_, _ = rec.Body.WriteTo(w)
})
}