-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
81 lines (60 loc) · 1.32 KB
/
main.go
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
75
76
77
78
79
80
81
package main
import (
"bytes"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
var tmpl *template.Template
func init() {
tmpl = template.Must(template.New("output").Parse(TEMPLATE))
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/{rest:.*}", handler)
// router.HandleFunc("/echo", handler)
loggedRouter := handlers.LoggingHandler(os.Stdout, router)
log.Printf("starting http-echo-server on :7000")
log.Fatal(http.ListenAndServe(":7000", loggedRouter))
}
func handler(w http.ResponseWriter, r *http.Request) {
var b bytes.Buffer
w.Header().Set("Content-Type", "text/plain")
err := r.Header.Write(&b)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, err)
}
headers := b.String()
b.Reset()
buf, _ := ioutil.ReadAll(r.Body)
// b = bytes.NewBuffer(buf)
body := string(buf)
b.Reset()
t := struct {
Req *http.Request
Headers string
Body string
}{
Req: r,
Headers: headers,
Body: body,
}
err = tmpl.Execute(&b, t)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, err)
}
w.WriteHeader(http.StatusOK)
w.Write(b.Bytes())
return
}
const TEMPLATE = `{{ .Req.Method }} {{ .Req.URL.String }} {{ .Req.Proto }}
{{ .Headers }}
{{ .Body }}
`