使用os.Getwd()获取文件路径以及**filepath.Join()**解决相对路径访问问题
使用gin来渲染模板时,一直找不到指定路径下的模板文件,使用绝对路径可以输出,但是相对路径就会出现问题。后来发现应该是go mod运行时的路径不是原本所在的路径,如果单纯使用相对路径也就相当于刻舟求剑。
解决办法:
首先我的文件路径如下:
templates.go是我要运行的程序,
package mainimport ("fmt""html/template""net/http""os""path/filepath"
)type User struct {Name stringgender stringAge int
}func teplatetest(w http.ResponseWriter, r *http.Request){//解析模板//使用绝对路径//template, err := template.ParseFiles("E:\\Go\\workspace\\study\\go-study\\templates\\hello.tmpl")//获取当前文件路径cur, _ := os.Getwd()filename := filepath.Join(cur, "templates/hello.tmpl")template, err := template.ParseFiles(filename)if err != nil{fmt.Println("Parse template failed,err:",err)return}//渲染模板name := "静静"//user1 := User{// Name: "张三",// gender: "男",// Age: 18,//}err = template.Execute(w, name)//err = template.Execute(w, user1)if err != nil{fmt.Println("render template failed,err:",err)return}
}func main() {http.HandleFunc("/", teplatetest)err := http.ListenAndServe(":9090", nil)if err != nil{fmt.Println("HTTP serve start failed,err:",err)return}
}