Merge pull request #69013 from ibrasho-forks/switch-to-http.Error

Update usages of http.ResponseWriter.WriteHeader to use http.Error
pull/58/head
k8s-ci-robot 2018-10-23 15:31:55 -07:00 committed by GitHub
commit dad07683b1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 29 additions and 32 deletions

View File

@ -140,7 +140,7 @@ func TestMarkMaster(t *testing.T) {
if req.URL.Path != "/api/v1/nodes/"+hostname { if req.URL.Path != "/api/v1/nodes/"+hostname {
t.Errorf("MarkMaster(%s): request for unexpected HTTP resource: %v", tc.name, req.URL.Path) t.Errorf("MarkMaster(%s): request for unexpected HTTP resource: %v", tc.name, req.URL.Path)
w.WriteHeader(http.StatusNotFound) http.Error(w, "", http.StatusNotFound)
return return
} }
@ -150,7 +150,7 @@ func TestMarkMaster(t *testing.T) {
patchRequest = toString(req.Body) patchRequest = toString(req.Body)
default: default:
t.Errorf("MarkMaster(%s): request for unexpected HTTP verb: %v", tc.name, req.Method) t.Errorf("MarkMaster(%s): request for unexpected HTTP verb: %v", tc.name, req.Method)
w.WriteHeader(http.StatusNotFound) http.Error(w, "", http.StatusNotFound)
return return
} }

View File

@ -120,7 +120,7 @@ func makeTestServer(t *testing.T, namespace string) (*httptest.Server, *utiltest
mux.Handle(testapi.Default.ResourcePath("endpoints/", namespace, ""), &fakeEndpointsHandler) mux.Handle(testapi.Default.ResourcePath("endpoints/", namespace, ""), &fakeEndpointsHandler)
mux.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) { mux.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
t.Errorf("unexpected request: %v", req.RequestURI) t.Errorf("unexpected request: %v", req.RequestURI)
res.WriteHeader(http.StatusNotFound) http.Error(res, "", http.StatusNotFound)
}) })
return httptest.NewServer(mux), &fakeEndpointsHandler return httptest.NewServer(mux), &fakeEndpointsHandler
} }

View File

@ -252,7 +252,7 @@ type debugHTTPHandler struct {
func (h *debugHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { func (h *debugHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/graph" { if req.URL.Path != "/graph" {
w.WriteHeader(http.StatusNotFound) http.Error(w, "", http.StatusNotFound)
return return
} }
@ -270,8 +270,7 @@ func (h *debugHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
data, err := dot.Marshal(graph, "full", "", " ", false) data, err := dot.Marshal(graph, "full", "", " ", false)
if err != nil { if err != nil {
w.Write([]byte(err.Error())) http.Error(w, err.Error(), http.StatusInternalServerError)
w.WriteHeader(http.StatusInternalServerError)
return return
} }
w.Write(data) w.Write(data)

View File

@ -70,7 +70,7 @@ func TestDockerKeyringFromGoogleDockerConfigMetadata(t *testing.T) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
fmt.Fprintln(w, sampleDockerConfig) fmt.Fprintln(w, sampleDockerConfig)
} else { } else {
w.WriteHeader(http.StatusNotFound) http.Error(w, "", http.StatusNotFound)
} }
})) }))
defer server.Close() defer server.Close()
@ -148,7 +148,7 @@ func TestDockerKeyringFromGoogleDockerConfigMetadataUrl(t *testing.T) {
w.Header().Set("Content-Type", "application/text") w.Header().Set("Content-Type", "application/text")
fmt.Fprint(w, "http://foo.bar.com"+valueEndpoint) fmt.Fprint(w, "http://foo.bar.com"+valueEndpoint)
} else { } else {
w.WriteHeader(http.StatusNotFound) http.Error(w, "", http.StatusNotFound)
} }
})) }))
defer server.Close() defer server.Close()
@ -232,7 +232,7 @@ func TestContainerRegistryBasics(t *testing.T) {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "default/\ncustom") fmt.Fprintln(w, "default/\ncustom")
} else { } else {
w.WriteHeader(http.StatusNotFound) http.Error(w, "", http.StatusNotFound)
} }
})) }))
defer server.Close() defer server.Close()
@ -291,7 +291,7 @@ func TestContainerRegistryNoServiceAccount(t *testing.T) {
} }
fmt.Fprintln(w, string(bytes)) fmt.Fprintln(w, string(bytes))
} else { } else {
w.WriteHeader(http.StatusNotFound) http.Error(w, "", http.StatusNotFound)
} }
})) }))
defer server.Close() defer server.Close()
@ -335,7 +335,7 @@ func TestContainerRegistryNoStorageScope(t *testing.T) {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "default/\ncustom") fmt.Fprintln(w, "default/\ncustom")
} else { } else {
w.WriteHeader(http.StatusNotFound) http.Error(w, "", http.StatusNotFound)
} }
})) }))
defer server.Close() defer server.Close()
@ -380,7 +380,7 @@ func TestComputePlatformScopeSubstitutesStorageScope(t *testing.T) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
fmt.Fprintln(w, "default/\ncustom") fmt.Fprintln(w, "default/\ncustom")
} else { } else {
w.WriteHeader(http.StatusNotFound) http.Error(w, "", http.StatusNotFound)
} }
})) }))
defer server.Close() defer server.Close()
@ -410,7 +410,7 @@ func TestComputePlatformScopeSubstitutesStorageScope(t *testing.T) {
func TestAllProvidersNoMetadata(t *testing.T) { func TestAllProvidersNoMetadata(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound) http.Error(w, "", http.StatusNotFound)
})) }))
defer server.Close() defer server.Close()

View File

@ -140,8 +140,7 @@ func (f *FilterServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
return return
} }
glog.V(3).Infof("Filter rejecting %v %v %v", req.Method, req.URL.Path, host) glog.V(3).Infof("Filter rejecting %v %v %v", req.Method, req.URL.Path, host)
rw.WriteHeader(http.StatusForbidden) http.Error(rw, http.StatusText(http.StatusForbidden), http.StatusForbidden)
rw.Write([]byte("<h3>Unauthorized</h3>"))
} }
// Server is a http.Handler which proxies Kubernetes APIs to remote API server. // Server is a http.Handler which proxies Kubernetes APIs to remote API server.

View File

@ -125,8 +125,7 @@ func createStreams(req *http.Request, w http.ResponseWriter, opts *Options, supp
func createHttpStreamStreams(req *http.Request, w http.ResponseWriter, opts *Options, supportedStreamProtocols []string, idleTimeout, streamCreationTimeout time.Duration) (*context, bool) { func createHttpStreamStreams(req *http.Request, w http.ResponseWriter, opts *Options, supportedStreamProtocols []string, idleTimeout, streamCreationTimeout time.Duration) (*context, bool) {
protocol, err := httpstream.Handshake(req, w, supportedStreamProtocols) protocol, err := httpstream.Handshake(req, w, supportedStreamProtocols)
if err != nil { if err != nil {
w.WriteHeader(http.StatusBadRequest) http.Error(w, err.Error(), http.StatusBadRequest)
fmt.Fprint(w, err.Error())
return nil, false return nil, false
} }

View File

@ -57,7 +57,7 @@ func TestHTTPProbeChecker(t *testing.T) {
if r.URL.Path == "/" { if r.URL.Path == "/" {
http.Redirect(w, r, "/new", s) http.Redirect(w, r, "/new", s)
} else if bad && r.URL.Path == "/new" { } else if bad && r.URL.Path == "/new" {
w.WriteHeader(http.StatusInternalServerError) http.Error(w, "", http.StatusInternalServerError)
} }
} }
} }

View File

@ -136,12 +136,12 @@ func Handshake(req *http.Request, w http.ResponseWriter, serverProtocols []strin
negotiatedProtocol := negotiateProtocol(clientProtocols, serverProtocols) negotiatedProtocol := negotiateProtocol(clientProtocols, serverProtocols)
if len(negotiatedProtocol) == 0 { if len(negotiatedProtocol) == 0 {
w.WriteHeader(http.StatusForbidden)
for i := range serverProtocols { for i := range serverProtocols {
w.Header().Add(HeaderAcceptedProtocolVersions, serverProtocols[i]) w.Header().Add(HeaderAcceptedProtocolVersions, serverProtocols[i])
} }
fmt.Fprintf(w, "unable to upgrade: unable to negotiate protocol: client supports %v, server accepts %v", clientProtocols, serverProtocols) err := fmt.Errorf("unable to upgrade: unable to negotiate protocol: client supports %v, server accepts %v", clientProtocols, serverProtocols)
return "", fmt.Errorf("unable to upgrade: unable to negotiate protocol: client supports %v, server supports %v", clientProtocols, serverProtocols) http.Error(w, err.Error(), http.StatusForbidden)
return "", err
} }
w.Header().Add(HeaderProtocolVersion, negotiatedProtocol) w.Header().Add(HeaderProtocolVersion, negotiatedProtocol)

View File

@ -74,15 +74,15 @@ func (u responseUpgrader) UpgradeResponse(w http.ResponseWriter, req *http.Reque
connectionHeader := strings.ToLower(req.Header.Get(httpstream.HeaderConnection)) connectionHeader := strings.ToLower(req.Header.Get(httpstream.HeaderConnection))
upgradeHeader := strings.ToLower(req.Header.Get(httpstream.HeaderUpgrade)) upgradeHeader := strings.ToLower(req.Header.Get(httpstream.HeaderUpgrade))
if !strings.Contains(connectionHeader, strings.ToLower(httpstream.HeaderUpgrade)) || !strings.Contains(upgradeHeader, strings.ToLower(HeaderSpdy31)) { if !strings.Contains(connectionHeader, strings.ToLower(httpstream.HeaderUpgrade)) || !strings.Contains(upgradeHeader, strings.ToLower(HeaderSpdy31)) {
w.WriteHeader(http.StatusBadRequest) errorMsg := fmt.Sprintf("unable to upgrade: missing upgrade headers in request: %#v", req.Header)
fmt.Fprintf(w, "unable to upgrade: missing upgrade headers in request: %#v", req.Header) http.Error(w, errorMsg, http.StatusBadRequest)
return nil return nil
} }
hijacker, ok := w.(http.Hijacker) hijacker, ok := w.(http.Hijacker)
if !ok { if !ok {
w.WriteHeader(http.StatusInternalServerError) errorMsg := fmt.Sprintf("unable to upgrade: unable to hijack response")
fmt.Fprintf(w, "unable to upgrade: unable to hijack response") http.Error(w, errorMsg, http.StatusInternalServerError)
return nil return nil
} }

View File

@ -33,7 +33,7 @@ func TestFailedAuthnAudit(t *testing.T) {
policyChecker := policy.FakeChecker(auditinternal.LevelRequestResponse, nil) policyChecker := policy.FakeChecker(auditinternal.LevelRequestResponse, nil)
handler := WithFailedAuthenticationAudit( handler := WithFailedAuthenticationAudit(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized) http.Error(w, "", http.StatusUnauthorized)
}), }),
sink, policyChecker) sink, policyChecker)
req, _ := http.NewRequest("GET", "/api/v1/namespaces/default/pods", nil) req, _ := http.NewRequest("GET", "/api/v1/namespaces/default/pods", nil)
@ -65,7 +65,7 @@ func TestFailedMultipleAuthnAudit(t *testing.T) {
policyChecker := policy.FakeChecker(auditinternal.LevelRequestResponse, nil) policyChecker := policy.FakeChecker(auditinternal.LevelRequestResponse, nil)
handler := WithFailedAuthenticationAudit( handler := WithFailedAuthenticationAudit(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized) http.Error(w, "", http.StatusUnauthorized)
}), }),
sink, policyChecker) sink, policyChecker)
req, _ := http.NewRequest("GET", "/api/v1/namespaces/default/pods", nil) req, _ := http.NewRequest("GET", "/api/v1/namespaces/default/pods", nil)
@ -98,7 +98,7 @@ func TestFailedAuthnAuditWithoutAuthorization(t *testing.T) {
policyChecker := policy.FakeChecker(auditinternal.LevelRequestResponse, nil) policyChecker := policy.FakeChecker(auditinternal.LevelRequestResponse, nil)
handler := WithFailedAuthenticationAudit( handler := WithFailedAuthenticationAudit(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized) http.Error(w, "", http.StatusUnauthorized)
}), }),
sink, policyChecker) sink, policyChecker)
req, _ := http.NewRequest("GET", "/api/v1/namespaces/default/pods", nil) req, _ := http.NewRequest("GET", "/api/v1/namespaces/default/pods", nil)
@ -129,7 +129,7 @@ func TestFailedAuthnAuditOmitted(t *testing.T) {
policyChecker := policy.FakeChecker(auditinternal.LevelRequestResponse, []auditinternal.Stage{auditinternal.StageResponseStarted}) policyChecker := policy.FakeChecker(auditinternal.LevelRequestResponse, []auditinternal.Stage{auditinternal.StageResponseStarted})
handler := WithFailedAuthenticationAudit( handler := WithFailedAuthenticationAudit(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized) http.Error(w, "", http.StatusUnauthorized)
}), }),
sink, policyChecker) sink, policyChecker)
req, _ := http.NewRequest("GET", "/api/v1/namespaces/default/pods", nil) req, _ := http.NewRequest("GET", "/api/v1/namespaces/default/pods", nil)

View File

@ -45,8 +45,8 @@ const (
var nonMutatingRequestVerbs = sets.NewString("get", "list", "watch") var nonMutatingRequestVerbs = sets.NewString("get", "list", "watch")
func handleError(w http.ResponseWriter, r *http.Request, err error) { func handleError(w http.ResponseWriter, r *http.Request, err error) {
w.WriteHeader(http.StatusInternalServerError) errorMsg := fmt.Sprintf("Internal Server Error: %#v", r.RequestURI)
fmt.Fprintf(w, "Internal Server Error: %#v", r.RequestURI) http.Error(w, errorMsg, http.StatusInternalServerError)
glog.Errorf(err.Error()) glog.Errorf(err.Error())
} }

View File

@ -60,7 +60,7 @@ func TestGetEtcdVersion_ValidVersion(t *testing.T) {
func TestGetEtcdVersion_ErrorStatus(t *testing.T) { func TestGetEtcdVersion_ErrorStatus(t *testing.T) {
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusServiceUnavailable) http.Error(w, "", http.StatusServiceUnavailable)
})) }))
defer testServer.Close() defer testServer.Close()