{“错误”:“不支持Content-Type标头[]”,“状态”:406}使用Golang将数据插入Elasticsearch时

Does anyone know how to fix this error?

I use Golang to insert data into elasticsearch, but it seems that there is no data inserted because of this error.

{"error":"Content-Type header [] is not supported","status":406}

I already set the content type. Note that I use elasticsearch 6.4.3

request, err := http.NewRequest("POST", urlSearch, bytes.NewBuffer(query))
            request.Close = true
            request.Header.Set("Content-Type", "application/json")

Last but not least, I use elastigo package to make requests to elasticsearch.

That's a strange response, as it suggests that this line:

request.Header.Set("Content-Type", "application/json")

Failed to add the value to the key slice. In modern go that does not happen, e.g.

data := []byte(`{"a":1}`)
req, err := http.NewRequest("POST", "", bytes.NewBuffer(data))
if err != nil {
    fmt.Println(err)
    return
}
req.Header.Set("Foo", "Bar")
fmt.Printf("%v
", req.Header)

Prints

map[Foo:[Bar]]

See go playground.

Are you using older version of Go that doesn't match that behavior? (I'm on 1.11.2 locally.)

Five suggestions:

(1) Handle the err return value from NewRequest to verify there's no problem there (see example above).

(2) Print the request Header value before send to verify it looks right at that point (see example above).

(3) Try the Add method for the Content-Type header instead of Set as an alternative:

func (h Header) Add(key, value string)

(4) Verify that you're not going through a proxy that strips header values.

(5) Verify that "application/json" is an acceptable content type for the endpoint you're hitting, as the empty value in the error response could be erroneous itself.

Good luck!