Skip to content

Commit

Permalink
Merge pull request #60 from cabify/colega/pass-correct-status-code-to…
Browse files Browse the repository at this point in the history
…-after-func

Pass the correct status code to AfterFunc
  • Loading branch information
kisielk authored Mar 25, 2019
2 parents 97c3400 + dcfeecf commit bffcfa7
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions v2/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ func (s *Server) HasMethod(method string) bool {
// ServeHTTP
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
WriteError(w, 405, "rpc: POST method required, received "+r.Method)
WriteError(w, http.StatusMethodNotAllowed, "rpc: POST method required, received "+r.Method)
return
}
contentType := r.Header.Get("Content-Type")
Expand All @@ -162,26 +162,26 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
codec = c
}
} else if codec = s.codecs[strings.ToLower(contentType)]; codec == nil {
WriteError(w, 415, "rpc: unrecognized Content-Type: "+contentType)
WriteError(w, http.StatusUnsupportedMediaType, "rpc: unrecognized Content-Type: "+contentType)
return
}
// Create a new codec request.
codecReq := codec.NewRequest(r)
// Get service method to be called.
method, errMethod := codecReq.Method()
if errMethod != nil {
codecReq.WriteError(w, 400, errMethod)
codecReq.WriteError(w, http.StatusBadRequest, errMethod)
return
}
serviceSpec, methodSpec, errGet := s.services.get(method)
if errGet != nil {
codecReq.WriteError(w, 400, errGet)
codecReq.WriteError(w, http.StatusBadRequest, errGet)
return
}
// Decode the args.
args := reflect.New(methodSpec.argsType)
if errRead := codecReq.ReadRequest(args.Interface()); errRead != nil {
codecReq.WriteError(w, 400, errRead)
codecReq.WriteError(w, http.StatusBadRequest, errRead)
return
}

Expand Down Expand Up @@ -227,18 +227,22 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {

// Extract the result to error if needed.
var errResult error
if !errValue[0].IsNil() {
errResult = errValue[0].Interface().(error)
statusCode := http.StatusOK
errInter := errValue[0].Interface()
if errInter != nil {
statusCode = http.StatusBadRequest
errResult = errInter.(error)
}

// Prevents Internet Explorer from MIME-sniffing a response away
// from the declared content-type
w.Header().Set("x-content-type-options", "nosniff")

// Encode the response.
if errResult == nil {
codecReq.WriteResponse(w, reply.Interface())
} else {
codecReq.WriteError(w, 400, errResult)
codecReq.WriteError(w, statusCode, errResult)
}

// Call the registered After Function
Expand All @@ -247,7 +251,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
Request: r,
Method: method,
Error: errResult,
StatusCode: 200,
StatusCode: statusCode,
})
}
}
Expand Down

0 comments on commit bffcfa7

Please sign in to comment.