網頁

2022/6/10

Golang Web接收表單資料

Go HTTP Web接收HTML表單上傳的資料。


範例環境:

  • Go 1.18


表單

建立下面HTML表單來提交資料。

demo.html

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <form action="http://localhost:8080/employee" method="POST">
        name:<input name="name" type="text"><br>
        email:<input name="email" type="email"><br>
        age:<input name="age" type="number"><br>
        birthday:<input name="birthday" type="date"><br>
        gender:
            <label><input type="radio" name="gender" value="male">male</label>
            <label><input type="radio" name="gender" value="female">female</label>
            <label><input type="radio" name="gender" value="others">others</label>
        <br>
        languages:
            <label><input type="checkbox" name="lang" value="en">english</label>
            <label><input type="checkbox" name="lang" value="ch">mandarin</label>
            <label><input type="checkbox" name="lang" value="jp">japanese</label>
        <br>
        <input type="submit">
    </form>
</body>
</html>


取得表單資料

下面建立一個POST|/employee API接收從表單上傳的檔案。要先調用http.Requset.ParseForm()才能從http.Request.Form以欄位名取得表單資料。

main.go

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/employee", func(w http.ResponseWriter, r *http.Request) {
        switch r.Method {
        case http.MethodPost:
            r.ParseForm()
            name := r.Form.Get("name")
            email := r.Form.Get("email")
            age := r.Form.Get("age")
            birthday := r.Form.Get("birthday")
            gender := r.Form.Get("gender")
            langs := r.Form["lang"] // langs type is []string

            fmt.Fprint(w, fmt.Sprintf(
                "name=%v\nemail=%v\nage=%v\nbirtyday=%v\ngender=%v\nlanguages=%v",
                name, email, age, birthday, gender, langs))
        default:
            http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        }
    })

    http.ListenAndServe(":8080", nil)
}

github


測試

啟動專案,在瀏覽器開啟表單輸入資料如下。

name:
email:
age:
birthday:
gender:
languages:

點選Submit提交結果如下。




或用curl發送form request,content-type設為application/x-www-form-urlencoded

$ curl -X POST "http://localhost:8080/employee" \
> -H 'content-type: application/x-www-form-urlencoded' \
> -d "name=John&email=john@abc.com&age=33&birthday=1989-04-12&gender=male&lang=en,ch,jp"

回應結果。

name=John
email=john@abc.com
age=33
birtyday=1989-04-12
gender=male
languages=[en,ch,jp]


沒有留言:

張貼留言