学习 golang 中,处理表单的输入一节报错:no such file or dir
本文介绍了学习 golang 中,处理表单的输入一节报错:no such file or dir的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
通过看谢老师的书,学golang,到了表单这里,处理表单的输入一节课的时候,遇到了错误,尝试了多个目录,都没找到究竟是哪个目录。不说了,上码求指点:
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"strings"
)
func sayhelloName(w http.ResponseWriter, r *http.Request) {
r.ParseForm() // 解析 URL 传递的参数,对于 post 则解析响应包的主体(request body)
// 注意:如果没有调用 ParseForm 方法,下面无法获取表单的数据
fmt.Println(r.Form) // 这些信息是输出到服务器端的打印信息
fmt.Println("path", r.URL.Path)
fmt.Println("scheme", r.URL.Scheme)
fmt.Println(r.Form["url_long"])
for k, v := range r.Form {
fmt.Println("key:", k)
fmt.Println("val:", strings.Join(v, ""))
}
fmt.Fprintf(w, "Hello April") // 这个写入到 w 的是输出客户端的
}
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method) // 获取请求的方法
if r.Method == "GET" {
t, terr := template.ParseFiles("login.gtpl")
//此处报错:说找不到 login.gtpl 文件,郁闷……
fmt.Println(t)
fmt.Println(terr)
// t.Execute(w, nil)
} else {
r.ParseForm()
// 请求的是登录数据,那么执行登录的逻辑判断
fmt.Println("username:", r.Form["username"])
fmt.Println("password:", r.Form["password"])
}
}
func main() {
http.HandleFunc("/", sayhelloName) // 设置访问路由
http.HandleFunc("/login", login) // 设置访问路由
err := http.ListenAndServe(":9090", nil) // 设置监听路由端口
if err != nil {
log.Fatal("ListenAndServe:", err)
}
}
项目结构:
我的错误信息:
模板文件的权限也给到了777,但是依然是这个错误
也尝试着换了几个目录,同样是这个错误,no such file or directory
解决方案
你可以打印看看项目运行时当前目录是什么。
// https://golang.org/pkg/os/#Getwd
wd, err := os.GetWd()
fmt.Println(wd)
fmt.Println(err)
t, terr := template.ParseFiles("login.gtpl")
这样做的话你是用的相对路径,需要你直接在login.gtpl所在的dir里跑你的程序。用绝对路径可以避免这个问题。
这篇关于学习 golang 中,处理表单的输入一节报错:no such file or dir的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文