echo icon indicating copy to clipboard operation
echo copied to clipboard

i want to collect all the http response from the server. how to make it?

Open heimao63531 opened this issue 6 years ago • 2 comments

i want to collect all the http response from the server. how to make it?

Checklist

  • [ ] Dependencies installed
  • [ ] No typos
  • [ ] Searched existing issues and docs

Expected behaviour

Actual behaviour

i have tried with echo.use(phonehome), but echo use will always run after router and before the API all. is there a way to collect the response?

Working code to debug

package main

func main() {
}

Version/commit

heimao63531 avatar Nov 11 '20 02:11 heimao63531

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"net"
	"net/http"

	"github.com/labstack/echo/v4"
)

type ResponseCollector struct {
	writer   http.ResponseWriter
	response *bytes.Buffer
}

func (r ResponseCollector) Hijack() (net.Conn, *bufio.ReadWriter, error) {
	return r.writer.(http.Hijacker).Hijack()
}

func (r ResponseCollector) Flush() {
	r.writer.(http.Flusher).Flush()
}

func (r ResponseCollector) Header() http.Header {
	return r.writer.Header()
}

func (r ResponseCollector) Write(bytes []byte) (int, error) {
	r.response.Write(bytes)
	return r.writer.Write(bytes)
}

func (r ResponseCollector) WriteHeader(statusCode int) {
	r.writer.WriteHeader(statusCode)
}

func collect(next echo.HandlerFunc) echo.HandlerFunc {
	return func(ctx echo.Context) error {
		writer := ResponseCollector{writer: ctx.Response().Writer, response: bytes.NewBuffer(nil)}
		ctx.Response().Writer = writer
		err := next(ctx)
		fmt.Println(writer.response.String())
		return err
	}
}

func main() {
	e := echo.New()

	e.Use(collect)
	e.GET("/hello", hello)

	e.Start(":9876")
}

func hello(ctx echo.Context) error {
	return ctx.JSON(
		http.StatusOK,
		echo.Map{"message": "welcome"},
	)
}

fanpei91 avatar Nov 11 '20 03:11 fanpei91

This seems to be answered, no comment from the original poster. So closing.

lammel avatar Mar 09 '21 12:03 lammel