我正在尝试构建一个简单的两个HandlerWeb 服务器。在第一个处理程序中,我从两个字段中提取值,即用户的名字和姓氏。在第二个处理程序中,我只是说,"Hello" (first name, last name).
我放了一个fmt.Println, 似乎我没有正确地将信息从第一个拉Handler回到 Go 编程中。这哪里出错了?
package main
import (
"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>
拉风的咖菲猫
相关分类