Go Web表单开发和处理中,可能会出现这样的问题:
2020/03/02 16:52:26 http: panic serving 127.0.0.1:52808: runtime error: invalid memory address or nil pointer dereference
goroutine 18 [running]:
这个问题出现的原因是Web表单的目录设置错误,导致读取表单文件失败。解决的方法是使用filepath.Join()设定文件路径
详细代码如下:
1、前端代码
<html> <head> <title></title> </head> <body> <form action="/login" method="post"> 用户名:<input type="text" name="username"> 密码:<input type="password" name="password"> <input type="submit" value="登录"> </form> </body> </html>
2、服务端代码
package main import ( "fmt" "log" "net/http" "path/filepath" "strings" "html/template" ) func helloworld(w http.ResponseWriter,r *http.Request){ r.ParseForm() fmt.Println(r.URL.Path) for k,v :=range r.Form{ fmt.Println(k) fmt.Println(strings.Join(v,"")) } fmt.Fprintf(w,"hello world!!!") } func login(w http.ResponseWriter,r *http.Request){ fmt.Println(r.Method) if r.Method=="GET"{ //t,_:=template.ParseFiles("login.gtpl") //错误设定的代码 t,_:=template.ParseFiles(filepath.Join("templates/", "login.gtpl")) // 正确的方法 }else{ r.ParseForm() fmt.Println(r.Form["username"]) fmt.Println(r.Form["password"]) } } func main(){ http.HandleFunc("/",helloworld) http.HandleFunc("/login",login) err:=http.ListenAndServe(":9090",nil) if err !=nil{ log.Fatal("listenandserver",err) } }
3、最终的目录结构
project_name
|-src
|-main.go
|-templates
|-login.gtpl