Go http發送表單範例。
範例環境:
- Go 1.18
範例
下面範例有兩個API,一為GET|/send
,一為POST|/employee
。GET|/send
中會將表單內容寫至http.Request.Body
後透過http.Client.Do()
發送請求給POST|/employee
。
url.Values
實為一個map,呼叫url.Values.Encode()
則將值編碼為url參數(name=John&age=33&...
)。
發送表單的請求頭(Request Header)的Content-Type
設為application/x-www-form-urlencoded
。
main.go
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
func main() {
http.HandleFunc("/send", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
form := url.Values{}
form.Add("name", "John")
form.Add("age", "33")
form.Add("lang", "en,ch,jp")
req, err := http.NewRequest(http.MethodPost, "http://localhost:8080/employee", strings.NewReader(form.Encode()))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
fmt.Fprint(w, string(b))
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
})
http.HandleFunc("/employee", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
r.ParseForm()
name := r.Form.Get("name")
age := r.Form.Get("age")
languages := r.Form["lang"]
fmt.Fprint(w, fmt.Sprintf("name=%v\nage=%v\nlanguages=%v", name, age, languages))
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
})
http.ListenAndServe(":8080", nil)
}
測試
使用curl輸入curl -X GET "http://localhost:8080/send"
,執行結果如下
$ curl -X GET "http://localhost:8080/send"
name=John
age=33
languages=[en,ch,jp]
沒有留言:
張貼留言