亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang,不從 HTML 傳遞值

Golang,不從 HTML 傳遞值

Go
慕姐8265434 2022-03-03 16:03:12
我正在嘗試構建一個簡單的兩個HandlerWeb 服務器。在第一個處理程序中,我從兩個字段中提取值,即用戶的名字和姓氏。在第二個處理程序中,我只是說,"Hello" (first name, last name).我放了一個fmt.Println, 似乎我沒有正確地將信息從第一個拉Handler回到 Go 編程中。這哪里出錯了?package mainimport (    "fmt"    "html/template"    "log"    "net/http")type Field struct {    Firstname  string    Secondname string}func RootHandler(w http.ResponseWriter, r *http.Request) {    tmpl, err := template.ParseFiles("index.html")    if err != nil {        fmt.Println("Index Template Parse Error: ", err)    }    err = tmpl.Execute(w, nil)    if err != nil {        fmt.Println("Index Template Execution Error: ", err)    }}func main() {    http.HandleFunc("/", RootHandler) // sets router    http.HandleFunc("/welcome", WelcomeHandler)    err := http.ListenAndServe(":4000", nil) // set listen port    if err != nil {        log.Fatal("ListenAndServe: ", err)    }}func WelcomeHandler(w http.ResponseWriter, r *http.Request) {    Firstname := r.FormValue("Namef")    Secondname := r.FormValue("Namel")    fmt.Println(Firstname)    f := new(Field)    f.Firstname = Firstname    f.Secondname = Secondname    fmt.Println(*f)    tmpl, err := template.ParseFiles("tmpl/welcome.tmpl")    if err != nil {        fmt.Println("Index Template Parse Error: ", err)    }    err = tmpl.Execute(w, &f)    if err != nil {        fmt.Println("Index Template Execution Error: ", err)    }}這是index.html我從中提取兩個值的:<!DOCTYPE html><html><body><form action="/welcome" method="post"><p> Welcome! First I will need your full name: </p>First Name: <input type="text" id="Namef" name="FirstName"><br>Last Name:  <input type="text" id="Namel" name="LastName" ><br><input type="submit" value="Next"></form><p>Click the "Submit" button and the form-data will be sent to a page on the server called "demo_form.asp".</p></body></html>
查看完整描述

1 回答

?
拉風的咖菲貓

TA貢獻1995條經驗 獲得超2個贊

問題是您嘗試使用錯誤的名稱獲取表單值。

name您必須使用您在 HTML 文檔中用作屬性的值,而不是id!

Firstname := r.FormValue("FirstName")
Secondname := r.FormValue("LastName")

這可能只是您的練習代碼,但絕不會在處理程序中解析模板。解析模板是一項相對占用資源的任務,您應該只執行一次,并且由于模板可以安全地并發使用,您可以使用template.Template來自多個 goroutine 的單個值(服務并發請求)。


查看完整回答
反對 回復 2022-03-03
  • 1 回答
  • 0 關注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號