Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Incorrect use of 406 Not Acceptable for incorrect content type #492

@cjbearman

Description

@cjbearman

I have a case where I am using JSON (for request/response). I am making a request that in fact includes an empty body. Technically of course, an empty body is not JSON. However the behavior I am seeing seems incorrect.

Consider the following simple application:

package main

import (
	"log"
	"net/http"

	"github.com/emicklei/go-restful/v3"
)

func main() {

	ws := new(restful.WebService)
	ws.
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)

	ws.Route(ws.POST("/test").To(test))
	restful.Add(ws)
	log.Fatal(http.ListenAndServe(":8080", nil))

}

type theResponse struct {
	Ok bool `json::"ok"`
}

func test(request *restful.Request, response *restful.Response) {
	response.WriteAsJson(&theResponse{Ok: true})
}

I can call the method thusly:

% curl -i http://localhost:8080/test -X POST -H Content-Type:application/json -H Accept:application/json
HTTP/1.1 200 OK
Content-Type: application/json
Date: Fri, 29 Apr 2022 21:28:54 GMT
Content-Length: 15

{
 "Ok": true
}

.. And that's all good. But since I don't actually have any POST content here, I would assume that I could omit the Content-Type header. And that's where things look wrong:

% curl -i http://localhost:8080/test -X POST -H Accept:application/json && echo                                 
HTTP/1.1 406 Not Acceptable
Date: Fri, 29 Apr 2022 21:29:30 GMT
Content-Length: 48
Content-Type: text/plain; charset=utf-8

406: Not Acceptable

Available representations: 

The problem here is two-fold.

Firstly, if there is no POST body, then one would assume that omitting the Content-Type header would be appropriate.
Secondly, and more significantly, the 406 status code is inappropriate in this case. A 406 Not Acceptable refers to the server being unable to produce the type requested by the Accept header. This is clearly not the case here. If it is necessary to return an error in this case, the appropriate error would be 415 Unsupported Media Type.

Reproduced as reported above, today on latest fetched version, specifically: github.com/emicklei/go-restful/v3 v3.3.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions