-14

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.

John Weldon
  • 39,849
  • 11
  • 94
  • 127
joshua29
  • 97
  • 1
  • 1
  • 9
  • 2
    Make an effort before you post a question. SO isn't the place for "write me some code", "convert my code", or "fix my code" questions. Try to solve the problem yourself, do some searching if you get stuck, then if you're stuck, post a question with what the problem is, what you've tried, and what didn't work. – 3ocene Sep 30 '16 at 18:57

1 Answers1

23

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.

Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • i try that answer. but didn't succeed. I need to input the port and host of server – joshua29 Nov 20 '14 at 08:10
  • @joshua29 it is a start, you can see more at http://golang.org/pkg/net/http/. Regarding "inputting" additional data, this is another question which is not part from your original question. – VonC Nov 20 '14 at 08:11
  • anyway, thanx for your reply. i will try again that solutions. – joshua29 Nov 20 '14 at 08:28
  • @joshua29 note that you can out your server and port number in the url. `http://yourServer:xx/...` – VonC Nov 20 '14 at 08:29
  • Pretty sure you need to import "io/ioutil" as well – Ingo May 03 '16 at 13:33
  • 1
    @Ingo I agree, and I have edited the answer accordingly. Thank you. – VonC May 03 '16 at 13:52