Go Web开发表单路径的问题

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值