[golang]結合url.Values發送post請求

server端示例:

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
        if r.Method == "POST" {
            var (
                name string = r.PostFormValue("name")
                id string = r.PostFormValue("id")
            )
            fmt.Printf("name-id is  : %s %s\n", name, id)
        }
    })

    err := http.ListenAndServe(":8888", nil)
    if err != nil {
        fmt.Println(err.Error())
        return
    }
}

client端示例

package main

import (
    "fmt"
    "net/http"
    "net/url"
    "strings"
)

func test1() {
    data := make(url.Values)
    data["name"] = []string{"xiaoming"}
    data["id"] = []string{"123456"}

    res, err := http.PostForm("http://127.0.0.1:8888/test", data)
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    defer res.Body.Close()
    fmt.Println("[PostForm] request1 sent successfully.")
}

func test2() {
	apiUrl := "http://127.0.0.1:8888"
    resource := "/test"
    data := url.Values{}
    data.Set("name", "xiaohua")
    data.Set("id", "654321")

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := u.String()

    client := &http.Client{}
    r, _ := http.NewRequest("POST", urlStr, strings.NewReader(data.Encode()))
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")

    resp, err := client.Do(r)
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    defer resp.Body.Close()
    fmt.Println("[client.Do] request2 sent successfully.")
}

func main() {
    test1()
    test2()
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章