// dumpResponse dumps the response and optionally the request (in case of JSON format) according to // DumpFormat. // It also checks whether the special recorder pipe is opened and if so writes the dump to it. func dumpResponse(resp *http.Response, req *http.Request, reqBody []byte) { if DumpFormat == NoDump { return } respBody, _ := dumpRespBody(resp) if DumpFormat.IsDebug() { var buffer bytes.Buffer buffer.WriteString("==> " + resp.Proto + " " + resp.Status + "\n") writeHeaders(&buffer, resp.Header) if respBody != nil { buffer.WriteString("\n") buffer.Write(respBody) buffer.WriteString("\n") } fmt.Fprint(OsStderr, buffer.String()) } else if DumpFormat.IsJSON() { reqHeaders := make(http.Header) filterHeaders(req.Header, func(name string, value []string) { reqHeaders[name] = value }) respHeaders := make(http.Header) filterHeaders(resp.Header, func(name string, value []string) { respHeaders[name] = value }) dumped := recording.RequestResponse{ Verb: req.Method, URI: req.URL.String(), ReqHeader: reqHeaders, ReqBody: string(reqBody), Status: resp.StatusCode, RespHeader: respHeaders, RespBody: string(respBody), } b, err := json.MarshalIndent(dumped, "", " ") if err != nil { log.Error("Failed to dump request content", "error", err.Error()) return } if DumpFormat.IsRecord() { f := os.NewFile(10, "fd10") _, err = f.Stat() if err == nil { // fd 10 is open, dump to it (used by recorder) fmt.Fprintf(f, "%s\n", string(b)) } } fmt.Fprint(OsStderr, string(b)) } }
// Dump request if needed. // Return request serialized as JSON if DumpFormat is JSON, nil otherwise. func dumpRequest(req *http.Request) []byte { if DumpFormat == NoDump { return nil } reqBody, err := dumpReqBody(req) if err != nil { log.Error("Failed to load request body for dump", "error", err.Error()) } if DumpFormat.IsDebug() { var buffer bytes.Buffer buffer.WriteString(req.Method + " " + req.URL.String() + "\n") writeHeaders(&buffer, req.Header) if reqBody != nil { buffer.WriteString("\n") buffer.Write(reqBody) buffer.WriteString("\n") } fmt.Fprint(OsStderr, buffer.String()) } else if DumpFormat.IsJSON() { return reqBody } return nil }