Golang 實現curl

  Linux很經常使用的curl命令,在golang中能夠使用net/http來實現php

模擬get請求

  func Get(url string) (resp *Response, err error)golang

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)app

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))
}
相關文章
相關標籤/搜索