創建Clinet請求POST、GET、PUT、DELETE
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"strings"
)
func main() {
client_POST("https://blog.oc-city.com")
client_GET("https://blog.oc-city.com")
client_PUT("https://blog.oc-city.com")
client_DELETE("https://blog.oc-city.com")
}
func client_GET(content string) {
//創建GET請求
resp, err := http.Get(content)
if err != nil {
fmt.Print(err, err)
}
close := resp.Body
bytes, err := io.ReadAll(close)
fmt.Println(string(bytes))
}
func client_POST(content string) {
//創建POST請求
url := content
post_ := "account=admin&password=admin" //發送POST數據
//post_ := "{\"account\":\"admin\",\"password\":\"admin\"}" //發送POST數據
response, err := http.Post(url, "application/x-www-form-urlencoded", bytes.NewBuffer([]byte(post_)))
if err != nil {
fmt.Println("err", err)
}
b, err := io.ReadAll(response.Body)
fmt.Print(string(b))
}
func client_PUT(content string) {
//創建PUT請求
url := content
payload := strings.NewReader("{\"account\":\"admin\",\"password\":\"passwd\"}")
req, _ := http.NewRequest("PUT", url, payload)
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(res)
fmt.Println(string(body))
}
func client_DELETE(content string) {
//創建DELETE請求
url := content
payload := strings.NewReader("{\"delete_id\":1,\"content\",\"留言A\":}")
req, _ := http.NewRequest("DELETE", url, payload)
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(res)
fmt.Println(string(body))
}
沒有留言:
張貼留言