Attempting to use libcurl to do a HTTP POST but en...
# kotlin-native
n
Attempting to use libcurl to do a HTTP POST but end up with this response from the Prometheus server:
Copy code
{
  "status": "error",
  "errorType": "bad_data",
  "error": "invalid parameter 'query': parse error at char 1: no expression found in input"
}
Can someone please confirm if I have correctly set the headers/body for the HTTP request. Below is the Kotlin code I am using:
Copy code
fun doHttpPost(url: String, headers: Map<String, String>, body: Map<String, String>): Unit = memScoped {
    val headersList = alloc<curl_slist>()
    headers.forEach { (k, v) -> curl_slist_append(headersList.ptr, "$k: $v") }
    curl_easy_setopt(curlPost, CURLOPT_URL, url)
    curl_easy_setopt(curlPost, CURLOPT_HTTPHEADER, headersList.next)
    curl_easy_setopt(curlPost, CURLOPT_POSTFIELDS, createPostBody(body))
    // Do HTTP POST.
    curl_easy_perform(curlPost)
}

fun createPostBody(args: Map<String, String>) = buildString {
    args.forEach { (k,v) -> append("&$k=$v") }
}.replaceFirst("&", "")
Originally
headersList.ptr
was passed as an argument to
curl_easy_setopt
however that caused a seg fault. Fixed the seg fault by passing through
headersList.next
instead, although I am not sure if that is the correct way to do it.
URL used in the request: http://xx.xx.xx.xx:xxxx/api/v1/query Trying to use the Prometheus Query API: https://prometheus.io/docs/prometheus/latest/querying/api/#instant-queries
Below is the function call being made to
doHttpPost
:
Copy code
doHttpPost(
        url = "http://$host:$port/api/v1/query",
        headers = mapOf("Content-Type" to "application/x-www-form-urlencoded"),
        body = mapOf("query" to "up")
    )
Based on the debug output from libcurl a HTTP POST call has been made, and multiple headers are being included in the request:
Copy code
*   Trying xx.xx.xx.xx...
* TCP_NODELAY set
* Connected to xx.xx.xx.xx (xx.xx.xx.xx) port xxxx (#0)
> POST /api/v1/query HTTP/1.1
Host: xx.xx.xx.xx:xxxx
Accept: */*
Content-Type: application/x-www-form-urlencoded
Size: 20
Content-Length: 6

* upload completely sent off: 6 out of 6 bytes
< HTTP/1.1 400 Bad Request
< Content-Type: application/json
< Date: Fri, 06 Mar 2020 02:04:00 GMT
< Content-Length: 130
< 
* Failed writing body (140695112576384 != 130)
* stopped the pause stream!
* Closing connection 0
What is strange is the error message about a HTTP body that can't be written (for the HTTP response?).
Wondering if there is a way for libcurl to print out the body of the HTTP request.
The linuxX64 version of Ktor Client uses libcurl under the hood. How does Ktor Client handle setting the body of a HTTP request (eg for a POST request) using libcurl