Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Invoke some callbacks before Write Header (for middleware) #831

Closed
itang opened this issue Jan 28, 2017 · 1 comment
Closed

Invoke some callbacks before Write Header (for middleware) #831

itang opened this issue Jan 28, 2017 · 1 comment
Assignees

Comments

@itang
Copy link

itang commented Jan 28, 2017

Invoke some callbacks before Write Header (for middleware)

  • Scenes to be used
// XRuntime Middleware
func XRuntime(next echo.HandlerFunc) echo.HandlerFunc {
	return func(ctx echo.Context) (err error) {
		start := time.Now()

		ctx.Response().OnBeforeWriteHeader(func(resp *echo.Response) {
			resp.Header().Set("x-runtime", time.Since(start).String())
		})

		return next(ctx)
	}
}

e := echo.New()
api := e.Group("/api", XRuntime)
  • Sample code
Response struct {
	Writer    http.ResponseWriter
	Status    int
	Size      int64
	Committed bool
	echo      *Echo
	writeHeaderCallbacks   []func(resp *Response)
}
	
func (r *Response) OnBeforeWriteHeader(callback func(resp *Response)) {
	r.writeHeaderCallbacks = append(r.writeHeaderCallbacks, callback)
}

func (r *Response) WriteHeader(code int) {
	if r.Committed {
		r.echo.Logger.Warn("response already committed")
		return
	}
	r.Status = code

	for _, callback := range r.writeHeaderCallbacks {
		callback(r)
	}

	r.Writer.WriteHeader(code)
	r.Committed = true
}

Please confirm echo to achieve similar functionality, what is the best practice?

@vishr
Copy link
Member

vishr commented Jun 28, 2017

May be related #176

@vishr vishr closed this as completed in f96c973 Jun 29, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants