Golang中如何获取表单数据

Golang中如何获取表单数据 我正在尝试从服务器获取表单数据,但屏幕上只打印出 []

我的 Go 代码如下:

package main

import (

"fmt"

"io/ioutil"

"net/http"

)

func check(e error) {

if e != nil {

panic(e)

}

}

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

r.ParseForm()

//fmt.Println(r.Form)

fmt.Println(r.Form["first_name"])

}

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

hpage, err := ioutil.ReadFile("index.html")

//fmt.Println("home page req")

check(err)

fmt.Fprintf(w, "%s", hpage)

}

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

page, err := ioutil.ReadFile("student.html")

fmt.Println("student page req")

check(err)

fmt.Fprintf(w, "%s", page)

}

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

page, err := ioutil.ReadFile("teacher.html")

//fmt.Println("teacher page req")

check(err)

fmt.Fprintf(w, "%s", page)

}

func main() {

http.HandleFunc("/", greet)

http.HandleFunc("/student", student)

http.HandleFunc("/teacher", teacher)

http.HandleFunc("/submit", submit)

j := http.ListenAndServe("192.168.0.14:8080", nil)

check(j)

}

这是我的 HTML 代码:

<form class="col s12" action="/submit" method="POST">
            <div class="row">
              <div class="input-field col s6">
                <input id="first_name" type="text" class="validate">
                <label for="first_name">Name of the teacher</label>
              </div>
              <div class="input-field col s6">
                <input id="last_name" type="text" class="validate">
                <label for="last_name">Subject</label>
              </div>
            </div>
            <div class="row">
              <div class="input-field col s12">
                <input id="studentid" type="text" class="validate">
                <label for="studentid">Student ID</label>
              </div>
            </div>
            <div class="row">
              <div class="input-field col s12">
                <input id="password" type="password" class="validate">
                <label for="password">Password</label>
              </div>
            </div>
           
           
            <p class="range-field ">
              <input type="range" id="K_level" min="0" max="100" />
              <label for="K_level">Knowledge level</label>
            </p>

            <p class="range-field ">
              <input type="range" id="param1" min="0" max="100" />
              <label for="param1">some parameter</label>
            </p>

            <p class="range-field ">
              <input type="range" id="param2" min="0" max="100" />
              <label for="param2">some parameter</label>
            </p>


            <button class="btn waves-effect waves-light pink" type="submit" name="action">Submit
              <i class="material-icons right">send</i>
            </button>

          </form>

更多关于Golang中如何获取表单数据的实战教程也可以访问 https://www.itying.com/category-94-b0.html

4 回复

你是否尝试将表单中的id属性改为name属性?

https://www.w3.org/TR/html5/sec-forms.html#forms-form-submission

更多关于Golang中如何获取表单数据的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


不要使用

r.Form["first_name"]

请使用

r.FormValue("first_name")

同时,在你的HTML代码中使用 name="first_name" 而不是 id="first_name"

techerjeansebastienp:

HTML 标准

我已经尝试了页面中的所有方法都失败了,不知道哪里出了问题,我只是照着教程复制的。

在你的代码中,打印 [] 是因为表单字段缺少 name 属性。Go 的 r.Formr.PostForm 只解析具有 name 属性的表单字段。

以下是修复后的 HTML 表单代码:

<form class="col s12" action="/submit" method="POST">
    <div class="row">
        <div class="input-field col s6">
            <input id="first_name" name="first_name" type="text" class="validate">
            <label for="first_name">Name of the teacher</label>
        </div>
        <div class="input-field col s6">
            <input id="last_name" name="last_name" type="text" class="validate">
            <label for="last_name">Subject</label>
        </div>
    </div>
    <div class="row">
        <div class="input-field col s12">
            <input id="studentid" name="studentid" type="text" class="validate">
            <label for="studentid">Student ID</label>
        </div>
    </div>
    <div class="row">
        <div class="input-field col s12">
            <input id="password" name="password" type="password" class="validate">
            <label for="password">Password</label>
        </div>
    </div>
   
    <p class="range-field">
        <input type="range" id="K_level" name="K_level" min="0" max="100" />
        <label for="K_level">Knowledge level</label>
    </p>

    <p class="range-field">
        <input type="range" id="param1" name="param1" min="0" max="100" />
        <label for="param1">some parameter</label>
    </p>

    <p class="range-field">
        <input type="range" id="param2" name="param2" min="0" max="100" />
        <label for="param2">some parameter</label>
    </p>

    <button class="btn waves-effect waves-light pink" type="submit" name="action">Submit
        <i class="material-icons right">send</i>
    </button>
</form>

同时,你的 Go 代码可以改进为更完整的表单处理:

func submit(w http.ResponseWriter, r *http.Request) {
    if r.Method != "POST" {
        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        return
    }
    
    // 解析表单数据
    if err := r.ParseForm(); err != nil {
        http.Error(w, "Error parsing form", http.StatusBadRequest)
        return
    }
    
    // 获取单个表单字段值
    firstName := r.FormValue("first_name")
    lastName := r.FormValue("last_name")
    studentID := r.FormValue("studentid")
    password := r.FormValue("password")
    kLevel := r.FormValue("K_level")
    param1 := r.FormValue("param1")
    param2 := r.FormValue("param2")
    
    // 打印所有表单值
    fmt.Printf("First Name: %s\n", firstName)
    fmt.Printf("Last Name: %s\n", lastName)
    fmt.Printf("Student ID: %s\n", studentID)
    fmt.Printf("Password: %s\n", password)
    fmt.Printf("Knowledge Level: %s\n", kLevel)
    fmt.Printf("Param1: %s\n", param1)
    fmt.Printf("Param2: %s\n", param2)
    
    // 或者使用 r.Form 获取所有值
    fmt.Println("All form values:", r.Form)
    
    // 或者获取特定字段的切片
    fmt.Println("First name values:", r.Form["first_name"])
}

主要修改点:

  1. 在 HTML 表单的所有输入字段中添加了 name 属性
  2. 在 Go 代码中添加了方法检查
  3. 使用 r.FormValue() 获取单个字段值
  4. 添加了错误处理

现在当你提交表单时,应该能够正确获取到所有表单数据而不是空切片。

回到顶部