rpc: minor cleanups to RPC PR

This commit is contained in:
Péter Szilágyi
2017-11-17 14:18:46 +02:00
parent c5b8569707
commit 3c6b9c5d72
2 changed files with 38 additions and 28 deletions

View File

@ -20,6 +20,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
@ -151,41 +152,36 @@ func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" && r.ContentLength == 0 && r.URL.RawQuery == "" {
return
}
if responseCode, errorMessage := httpErrorResponse(r); responseCode != 0 {
http.Error(w, errorMessage, responseCode)
if code, err := validateRequest(r); err != nil {
http.Error(w, err.Error(), code)
return
}
// All checks passed, create a codec that reads direct from the request body
// untilEOF and writes the response to w and order the server to process a
// single request.
codec := NewJSONCodec(&httpReadWriteNopCloser{r.Body, w})
defer codec.Close()
w.Header().Set("content-type", "application/json")
w.Header().Set("content-type", contentType)
srv.ServeSingleRequest(codec, OptionMethodInvocation)
}
// Returns a non-zero response code and error message if the request is invalid.
func httpErrorResponse(r *http.Request) (int, string) {
// validateRequest returns a non-zero response code and error message if the
// request is invalid.
func validateRequest(r *http.Request) (int, error) {
if r.Method == "PUT" || r.Method == "DELETE" {
errorMessage := "method not allowed"
return http.StatusMethodNotAllowed, errorMessage
return http.StatusMethodNotAllowed, errors.New("method not allowed")
}
if r.ContentLength > maxHTTPRequestContentLength {
errorMessage := fmt.Sprintf("content length too large (%d>%d)", r.ContentLength, maxHTTPRequestContentLength)
return http.StatusRequestEntityTooLarge, errorMessage
err := fmt.Errorf("content length too large (%d>%d)", r.ContentLength, maxHTTPRequestContentLength)
return http.StatusRequestEntityTooLarge, err
}
ct := r.Header.Get("content-type")
mt, _, err := mime.ParseMediaType(ct)
mt, _, err := mime.ParseMediaType(r.Header.Get("content-type"))
if err != nil || mt != contentType {
errorMessage := fmt.Sprintf("invalid content type, only %s is supported", contentType)
return http.StatusUnsupportedMediaType, errorMessage
err := fmt.Errorf("invalid content type, only %s is supported", contentType)
return http.StatusUnsupportedMediaType, err
}
return 0, ""
return 0, nil
}
func newCorsHandler(srv *Server, allowedOrigins []string) http.Handler {