Make ResponseWriter an interface

Make ResponseWriter an interface with an unexported method. Implementors
must embed a ResponseWriter from elsewhere. This gives us the
flexibility of an interface while allowing us to add new methods in the
future.
This commit is contained in:
Adnan Maolood
2021-02-24 00:13:44 -05:00
parent 526d232ab0
commit 3660698a4b
5 changed files with 92 additions and 65 deletions

View File

@@ -21,23 +21,23 @@ import (
//
// Handlers should not modify the provided Request.
type Handler interface {
ServeGemini(context.Context, *ResponseWriter, *Request)
ServeGemini(context.Context, ResponseWriter, *Request)
}
// The HandlerFunc type is an adapter to allow the use of ordinary functions
// as Gemini handlers. If f is a function with the appropriate signature,
// HandlerFunc(f) is a Handler that calls f.
type HandlerFunc func(context.Context, *ResponseWriter, *Request)
type HandlerFunc func(context.Context, ResponseWriter, *Request)
// ServeGemini calls f(ctx, w, r).
func (f HandlerFunc) ServeGemini(ctx context.Context, w *ResponseWriter, r *Request) {
func (f HandlerFunc) ServeGemini(ctx context.Context, w ResponseWriter, r *Request) {
f(ctx, w, r)
}
// StatusHandler returns a request handler that responds to each request
// with the provided status code and meta.
func StatusHandler(status Status, meta string) Handler {
return HandlerFunc(func(ctx context.Context, w *ResponseWriter, r *Request) {
return HandlerFunc(func(ctx context.Context, w ResponseWriter, r *Request) {
w.WriteHeader(status, meta)
})
}
@@ -58,7 +58,7 @@ func StripPrefix(prefix string, h Handler) Handler {
if prefix == "" {
return h
}
return HandlerFunc(func(ctx context.Context, w *ResponseWriter, r *Request) {
return HandlerFunc(func(ctx context.Context, w ResponseWriter, r *Request) {
p := strings.TrimPrefix(r.URL.Path, prefix)
rp := strings.TrimPrefix(r.URL.RawPath, prefix)
if len(p) < len(r.URL.Path) && (r.URL.RawPath == "" || len(rp) < len(r.URL.RawPath)) {
@@ -92,7 +92,7 @@ type timeoutHandler struct {
dt time.Duration
}
func (t *timeoutHandler) ServeGemini(ctx context.Context, w *ResponseWriter, r *Request) {
func (t *timeoutHandler) ServeGemini(ctx context.Context, w ResponseWriter, r *Request) {
ctx, cancel := context.WithTimeout(ctx, t.dt)
defer cancel()