Go net/http request

18.7k views Asked by At

Can somebody help to convert my ruby code to Go. Kindly refer to my ruby code below.

 query=       "test"
 request =        Net::HTTP::Post.new(url)
 request.body =     query
 response =   Net::HTTP.new(host, post).start{|http http.request(request)}   

to Go.

1

There are 1 answers

6
VonC On BEST ANSWER

You seem to want to POST a query, which would be similar to this answer:

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "net/http"
)


func main() {
    url := "http://xxx/yyy"
    fmt.Println("URL:>", url)

    var query = []byte(`your query`)
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(query))
    req.Header.Set("X-Custom-Header", "myvalue")
    req.Header.Set("Content-Type", "text/plain")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    fmt.Println("response Status:", resp.Status)
    fmt.Println("response Headers:", resp.Header)
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println("response Body:", string(body))
}

Replace "text/plain" with "application/json" if your query is a JSON one.