Go 从零开始(四)表单提交

 

一、创建表单

打印 html 标签字符串,并动态加入表单提交的路径。

func articlesCreateHandler(w http.ResponseWriter, r *http.Request) {
    html := `
<!DOCTYPE html>
<html lang="en">
<head>
    <title>创建文章</title>
</head>
<body>
    <form action="%s" method="post">
        <p><input type="text" name="title"></p>
        <p><textarea name="body" cols="30" rows="10"></textarea></p>
        <p><button type="submit">提交</button></p>
    </form>
</body>
</html>
`
    storeURL, _ := router.Get("articles.store").URL()
    fmt.Fprintf(w, html, storeURL)
}

 

二、接收表单提交的数据

上一步表单提交到了 store 方法。所以在以下 store 方法中可以获取表单数据。

func articlesStoreHandler(w http.ResponseWriter, r *http.Request) {

    err := r.ParseForm()
    if err != nil {
        // 解析错误,这里应该有错误处理
        fmt.Fprint(w,  "请提供正确的数据!")
        return
    }

    // PostForm 获取 post put 数据
    // 在使用之前需要调用 ParseForm 方法
    title := r.PostForm.Get("title")

    // Form 获取 post put get 数据
    // 在使用之前需要调用 ParseForm 方法
    title := r.Form.Get("title")

    // FormValue()、PostFormValue() 获取单个的值
    // 无需调用 ParseForm 方法
    title := r.PostFormValue("title")

    fmt.Fprintf(w, "PostForm: %v <br>", r.PostForm)
    fmt.Fprintf(w, "Form: %v <br>", r.Form)
    fmt.Fprintf(w, "title: %v", title)
}

 

posted @ 2022-06-29 10:51  菜乌  阅读(373)  评论(0编辑  收藏  举报