forked from virtual-kubelet/virtual-kubelet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go
84 lines (72 loc) · 1.92 KB
/
helpers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Copyright © 2017 The virtual-kubelet authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package api
import (
"io"
"net/http"
"github.com/virtual-kubelet/virtual-kubelet/errdefs"
"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 := httpStatusCode(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
}
func httpStatusCode(err error) int {
switch {
case err == nil:
return http.StatusOK
case errdefs.IsNotFound(err):
return http.StatusNotFound
case errdefs.IsInvalidInput(err):
return http.StatusBadRequest
default:
return http.StatusInternalServerError
}
}