在Go中请求URL

huangapple go评论78阅读模式
英文:

Request URL in Go

问题

我喜欢问一下,如何使用Go运行URL。我有一个Ruby代码,我想转换成Go。

import (
    "fmt"
    "net/http"
    "net/url"
)

func main() {
    url := "https://rest.nexmo.com/sms/xml?api_key=KEY&api_secret=SECRET&from=Aphelion&to=" + params["user"]["mobile_num"] + "&text=Test SMS"
    encodedURL := url.QueryEscape(url)
    req, err := http.NewRequest("GET", encodedURL, nil)
    if err != nil {
        fmt.Println(err)
        return
    }
    client := &http.Client{}
    res, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer res.Body.Close()
    // 处理响应
}

谢谢。

英文:

I like to ask, if how can i run URL using go. I have ruby code that i like to convert to Go.

url4 = "https://rest.nexmo.com/sms/xml?api_key=KEY&api_secret=SECRET&from=Aphelion&to=#{params[:user][:mobile_num]}&text=Test SMS"
encoded_url3 = URI.encode(url4)
url5= URI.parse(encoded_url3)
req3 = Net::HTTP::Get.new(url5.to_s)
res = Net::HTTP.start('rest.nexmo.com', 80) {|http|
  http.request(req3)
}

Thank you

答案1

得分: 2

标准的net/http包提供了一个默认的HTTP客户端,用于执行HTTP请求。

package main

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

func main() {
        resp, err := http.Get("https://rest.nexmo.com/sms/xml")
        if err != nil {
                panic(err)
        }
        defer resp.Body.Close()
        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
                panic(err)
        }
        fmt.Printf("%s", body)
}
英文:

The standard net/http package provides a default http client for performing http requests.

package main

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

func main() {
        resp, err := http.Get("https://rest.nexmo.com/sms/xml")
        if err != nil {
                panic(err)
        }
        defer resp.Body.Close()
        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
                panic(err)
        }
        fmt.Printf("%s", body)
}

huangapple
  • 本文由 发表于 2014年11月22日 12:56:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/27074195.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定