rpc: minor cleanups to RPC PR
This commit is contained in:
32
rpc/http.go
32
rpc/http.go
@ -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 {
|
||||
|
Reference in New Issue
Block a user