Golang 实现curl
Linux很常用的curl命令,在golang中可以使用net/http来实现
模拟get请求
func Get(url string) (resp *Response, err error)
package main import ( "fmt" "io/ioutil" "net/http" ) func main() { response, err := http.Get("http://www.baidu.com") if err != nil { panic(err) } defer response.Body.Close() body, err := ioutil.ReadAll(response.Body) fmt.Println(string(body)) }
模拟POST请求
func Post(url string, bodyType string, body io.Reader) (resp *Response, err error)
package main import ( "fmt" "io/ioutil" "net/http" "strings" ) func main() { response, err := http.Post( "http://localhost/index.php", "application/x-www-form-urlencoded", strings.NewReader("name=abc&age=99"), ) if err != nil { panic(err) } defer response.Body.Close() body, err := ioutil.ReadAll(response.Body) fmt.Println(string(body)) }
如需转载,请注明文章出处,谢谢!!!