Debian Codegraph @

pkg/registry/generic/rest/response_checker.go

raw
1 /*
2 Copyright 2014 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package rest
18
19 import (
20 "fmt"
21 "io"
22 "io/ioutil"
23 "net/http"
24
25 "k8s.io/apimachinery/pkg/api/errors"
26 "k8s.io/apimachinery/pkg/runtime/schema"
27 )
28
29 // Check the http error status from a location URL.
30 // And convert an error into a structured API object.
31 // Finally ensure we close the body before returning the error
32 type HttpResponseChecker interface {
33 Check(resp *http.Response) error
34 }
35
36 // Max length read from the response body of a location which returns error status
37 const (
38 maxReadLength = 50000
39 )
40
41 // A generic http response checker to transform the error.
42 type GenericHttpResponseChecker struct {
43 QualifiedResource schema.GroupResource
44 Name string
45 }
46
47 func (checker GenericHttpResponseChecker) Check(resp *http.Response) error {
48 if resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusPartialContent {
49 defer resp.Body.Close()
50 bodyBytes, err := ioutil.ReadAll(io.LimitReader(resp.Body, maxReadLength))
51 if err != nil {
52 return errors.NewInternalError(err)
53 }
54 bodyText := string(bodyBytes)
55
56 switch {
57 case resp.StatusCode == http.StatusInternalServerError:
58 return errors.NewInternalError(fmt.Errorf("%s", bodyText))
59 case resp.StatusCode == http.StatusBadRequest:
60 return errors.NewBadRequest(bodyText)
61 case resp.StatusCode == http.StatusNotFound:
62 return errors.NewGenericServerResponse(resp.StatusCode, "", checker.QualifiedResource, checker.Name, bodyText, 0, false)
63 }
64 return errors.NewGenericServerResponse(resp.StatusCode, "", checker.QualifiedResource, checker.Name, bodyText, 0, false)
65 }
66 return nil
67 }
68
69 func NewGenericHttpResponseChecker(qualifiedResource schema.GroupResource, name string) GenericHttpResponseChecker {
70 return GenericHttpResponseChecker{QualifiedResource: qualifiedResource, Name: name}
71 }