Linux很常用的curl命令,在golang中可以使用net/http来实现
模拟get请求
func Get(url string) (resp *Response, err error)
1package main 2 3import ( 4 "fmt" 5 "io/ioutil" 6 "net/http" 7) 8 9func main() { 10 response, err := http.Get("http://www.baidu.com") 11 if err != nil { 12 panic(err) 13 } 14 defer response.Body.Close() 15 body, err := ioutil.ReadAll(response.Body) 16 fmt.Println(string(body)) 17}
模拟POST请求
func Post(url string, bodyType string, body io.Reader) (resp *Response, err error)
1package main 2 3import ( 4 "fmt" 5 "io/ioutil" 6 "net/http" 7 "strings" 8) 9 10func main() { 11 response, err := http.Post( 12 "http://localhost/index.php", 13 "application/x-www-form-urlencoded", 14 strings.NewReader("name=abc&age=99"), 15 ) 16 if err != nil { 17 panic(err) 18 } 19 defer response.Body.Close() 20 body, err := ioutil.ReadAll(response.Body) 21 fmt.Println(string(body)) 22}