단순한 두 개의 Handler
웹 서버를 만들려고합니다. 첫 번째 처리기에서는 사용자의 이름과 성이라는 두 개의 필드에서 값을 가져옵니다. 두 번째 처리기에서 나는 단순히 진술하고있다, "Hello" (first name, last name)
.Golang, HTML에서 값을 전달하지 않음
나는 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>
이것은 도움이되었습니다. 명확하게하기 위해 선언에서 변수의 이름을 변경했습니다. 고맙습니다. –