英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论