-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.

1
  • 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. Commented Sep 30, 2016 at 18:57

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

i try that answer. but didn't succeed. I need to input the port and host of server
@joshua29 it is a start, you can see more at golang.org/pkg/net/http. Regarding "inputting" additional data, this is another question which is not part from your original question.
anyway, thanx for your reply. i will try again that solutions.
@joshua29 note that you can out your server and port number in the url. http://yourServer:xx/...
@Ingo I agree, and I have edited the answer accordingly. Thank you.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.