http: add allow func

For further extendability
release-2.0
Yicheng Qin 2014-09-09 15:44:34 -07:00
parent 4087fa5c7a
commit 961a61d708
2 changed files with 9 additions and 3 deletions

View File

@ -204,7 +204,7 @@ func (h Handler) serveKeys(ctx context.Context, w http.ResponseWriter, r *http.R
// TODO: rethink the format of machine list because it is not json format.
func (h Handler) serveMachines(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" && r.Method != "HEAD" {
w.WriteHeader(http.StatusMethodNotAllowed)
allow(w, "GET", "HEAD")
return
}
urls := make([]string, 0)
@ -349,3 +349,9 @@ func waitForEvent(ctx context.Context, w http.ResponseWriter, wa store.Watcher)
return nil, ctx.Err()
}
}
// allow writes response for the case that Method Not Allowed
func allow(w http.ResponseWriter, m ...string) {
w.Header().Set("Allow", strings.Join(m, ","))
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
}

View File

@ -363,7 +363,7 @@ func TestV2MachinesEndpoint(t *testing.T) {
defer s.Close()
for _, tt := range tests {
req, _ := http.NewRequest(tt.method, s.URL + machinesPrefix, nil)
req, _ := http.NewRequest(tt.method, s.URL+machinesPrefix, nil)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
@ -385,7 +385,7 @@ func TestServeMachines(t *testing.T) {
h.serveMachines(writer, req)
w := "http://localhost:8080, http://localhost:8081, http://localhost:8082"
if g := writer.Body.String(); g != w {
t.Errorf("data = %s, want %s", g, w)
t.Errorf("body = %s, want %s", g, w)
}
if writer.Code != http.StatusOK {
t.Errorf("header = %d, want %d", writer.Code, http.StatusOK)