Files
virtual-kubelet/vkubelet/api/helpers.go
Brian Goff 3cc051f7c2 Use I/O stream for provider logs interface
Providers must still update the implementaiton to actually gain any
benefit here, but this makes the provider interface a bit more sane.
2019-05-08 09:17:29 -07:00

58 lines
1.1 KiB
Go

package api
import (
"io"
"net/http"
"github.com/cpuguy83/strongerrors/status"
"github.com/virtual-kubelet/virtual-kubelet/log"
)
type handlerFunc func(http.ResponseWriter, *http.Request) error
func handleError(f handlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
err := f(w, req)
if err == nil {
return
}
code, _ := status.HTTPCode(err)
w.WriteHeader(code)
io.WriteString(w, err.Error())
logger := log.G(req.Context()).WithError(err).WithField("httpStatusCode", code)
if code >= 500 {
logger.Error("Internal server error on request")
} else {
logger.Debug("Error on request")
}
}
}
func flushOnWrite(w io.Writer) io.Writer {
if fw, ok := w.(writeFlusher); ok {
return &flushWriter{fw}
}
return w
}
type flushWriter struct {
w writeFlusher
}
type writeFlusher interface {
Flush() error
Write([]byte) (int, error)
}
func (fw *flushWriter) Write(p []byte) (int, error) {
n, err := fw.w.Write(p)
if n > 0 {
if err := fw.w.Flush(); err != nil {
return n, err
}
}
return n, err
}