Browse Source

proxy: return JSON errors

Xiang Li 11 years ago
parent
commit
6fa8f77638
2 changed files with 15 additions and 4 deletions
  1. 11 4
      proxy/reverse.go
  2. 4 0
      proxy/reverse_test.go

+ 11 - 4
proxy/reverse.go

@@ -17,12 +17,15 @@
 package proxy
 package proxy
 
 
 import (
 import (
+	"fmt"
 	"io"
 	"io"
 	"log"
 	"log"
 	"net"
 	"net"
 	"net/http"
 	"net/http"
 	"net/url"
 	"net/url"
 	"strings"
 	"strings"
+
+	"github.com/coreos/etcd/etcdserver/etcdhttp/httptypes"
 )
 )
 
 
 // Hop-by-hop headers. These are removed when sent to the backend.
 // Hop-by-hop headers. These are removed when sent to the backend.
@@ -64,8 +67,10 @@ func (p *reverseProxy) ServeHTTP(rw http.ResponseWriter, clientreq *http.Request
 
 
 	endpoints := p.director.endpoints()
 	endpoints := p.director.endpoints()
 	if len(endpoints) == 0 {
 	if len(endpoints) == 0 {
-		log.Printf("proxy: zero endpoints currently available")
-		rw.WriteHeader(http.StatusServiceUnavailable)
+		msg := "proxy: zero endpoints currently available"
+		log.Printf(msg)
+		e := httptypes.NewHTTPError(http.StatusServiceUnavailable, msg)
+		e.WriteTo(rw)
 		return
 		return
 	}
 	}
 
 
@@ -86,8 +91,10 @@ func (p *reverseProxy) ServeHTTP(rw http.ResponseWriter, clientreq *http.Request
 	}
 	}
 
 
 	if res == nil {
 	if res == nil {
-		log.Printf("proxy: unable to get response from %d endpoint(s)", len(endpoints))
-		rw.WriteHeader(http.StatusBadGateway)
+		msg := fmt.Sprintf("proxy: unable to get response from %d endpoint(s)", len(endpoints))
+		log.Printf(msg)
+		e := httptypes.NewHTTPError(http.StatusBadGateway, msg)
+		e.WriteTo(rw)
 		return
 		return
 	}
 	}
 
 

+ 4 - 0
proxy/reverse_test.go

@@ -70,6 +70,7 @@ func TestReverseProxyServe(t *testing.T) {
 				res: &http.Response{
 				res: &http.Response{
 					StatusCode: http.StatusCreated,
 					StatusCode: http.StatusCreated,
 					Body:       ioutil.NopCloser(&bytes.Reader{}),
 					Body:       ioutil.NopCloser(&bytes.Reader{}),
+					Header:     map[string][]string{"Content-Type": []string{"application/json"}},
 				},
 				},
 			},
 			},
 			want: http.StatusCreated,
 			want: http.StatusCreated,
@@ -89,6 +90,9 @@ func TestReverseProxyServe(t *testing.T) {
 		if rr.Code != tt.want {
 		if rr.Code != tt.want {
 			t.Errorf("#%d: unexpected HTTP status code: want = %d, got = %d", i, tt.want, rr.Code)
 			t.Errorf("#%d: unexpected HTTP status code: want = %d, got = %d", i, tt.want, rr.Code)
 		}
 		}
+		if gct := rr.Header().Get("Content-Type"); gct != "application/json" {
+			t.Errorf("#%d: Content-Type = %s, want %s", i, gct, "application/json")
+		}
 	}
 	}
 }
 }