Merge pull request #1685 from xiang90/proxy

proxy: return JSON errors
release-2.0
Xiang Li 2014-11-10 16:51:25 -08:00
commit 50ffd87831
2 changed files with 17 additions and 4 deletions

View File

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

View File

@ -70,6 +70,7 @@ func TestReverseProxyServe(t *testing.T) {
res: &http.Response{
StatusCode: http.StatusCreated,
Body: ioutil.NopCloser(&bytes.Reader{}),
Header: map[string][]string{"Content-Type": []string{"application/json"}},
},
},
want: http.StatusCreated,
@ -89,6 +90,9 @@ func TestReverseProxyServe(t *testing.T) {
if rr.Code != tt.want {
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")
}
}
}