move dump to get info

This commit is contained in:
Fabricio 2018-11-24 12:24:16 -02:00
parent e6f222c497
commit bdaa96ef56
2 changed files with 33 additions and 26 deletions

View file

@ -1,6 +1,7 @@
package main
import (
"net/http"
"strconv"
"sync"
)
@ -22,12 +23,9 @@ type CaptureList struct {
}
type Capture struct {
ID int `json:"id"`
Path string `json:"path"`
Method string `json:"method"`
Status int `json:"status"`
Request string `json:"request"`
Response string `json:"response"`
ID int
Req *http.Request
Res *http.Response
}
type CaptureMetadata struct {
@ -37,12 +35,17 @@ type CaptureMetadata struct {
Status int `json:"status"`
}
type CaptureDump struct {
Request string `json:"request"`
Response string `json:"response"`
}
func (c *Capture) Metadata() CaptureMetadata {
return CaptureMetadata{
ID: c.ID,
Path: c.Path,
Method: c.Method,
Status: c.Status,
Path: c.Req.URL.Path,
Method: c.Req.Method,
Status: c.Res.StatusCode,
}
}

38
main.go
View file

@ -82,7 +82,7 @@ func NewDashboardItemInfoHandler(repo CaptureRepository) http.Handler {
return
}
rw.Header().Add("Content-Type", "application/json")
json.NewEncoder(rw).Encode(capture)
json.NewEncoder(rw).Encode(dump(capture))
})
}
@ -109,34 +109,26 @@ func NewPlugin(next http.Handler) http.Handler {
func NewRecorder(repo CaptureRepository, next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
reqDump, err := dumpRequest(req)
if err != nil {
fmt.Printf("could not dump request: %v\n", err)
}
// save req body for later
var reqBody []byte
req.Body, reqBody = drain(req.Body)
rec := httptest.NewRecorder()
next.ServeHTTP(rec, req)
// respond
for k, v := range rec.HeaderMap {
rw.Header()[k] = v
}
rw.WriteHeader(rec.Code)
rw.Write(rec.Body.Bytes())
// record req and res
req.Body = ioutil.NopCloser(bytes.NewReader(reqBody))
res := rec.Result()
resDump, err := dumpResponse(res)
if err != nil {
fmt.Printf("could not dump response: %v\n", err)
}
capture := Capture{
Path: req.URL.Path,
Method: req.Method,
Status: res.StatusCode,
Request: string(reqDump),
Response: string(resDump),
}
repo.Insert(capture)
repo.Insert(Capture{Req: req, Res: res})
emitToDashboard(repo.FindAll())
})
}
@ -155,6 +147,18 @@ func NewProxyHandler(URL string) http.Handler {
})
}
func dump(c *Capture) CaptureDump {
reqDump, err := dumpRequest(c.Req)
if err != nil {
fmt.Printf("could not dump request: %v\n", err)
}
resDump, err := dumpResponse(c.Res)
if err != nil {
fmt.Printf("could not dump response: %v\n", err)
}
return CaptureDump{Request: string(reqDump), Response: string(resDump)}
}
func dumpRequest(req *http.Request) ([]byte, error) {
if req.Header.Get("Content-Encoding") == "gzip" {
var reqBody []byte