Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
open template.html:系统在GoLang中找不到指定的文件错误_Go - Fatal编程技术网

open template.html:系统在GoLang中找不到指定的文件错误

open template.html:系统在GoLang中找不到指定的文件错误,go,Go,总的来说,我对编程是个新手。我尝试使用Go创建一个网站,但不知怎么的,它无法读取我的HTML模板。我做错了什么?? 您正在从不同的目录运行代码;它将在当前目录中查找模板文件。您要填充的名称是相对于当前工作目录的,而不是使用文件名的.go文件。如何检查它?两者都在web目录中将此行添加到main():fmt.Println(os.Getwd())的开头。我想你会发现工作目录不是web目录。 package main import ( "fmt" "

总的来说,我对编程是个新手。我尝试使用Go创建一个网站,但不知怎么的,它无法读取我的HTML模板。我做错了什么??


您正在从不同的目录运行代码;它将在当前目录中查找模板文件。您要填充的名称是相对于当前工作目录的,而不是使用文件名的.go文件。如何检查它?两者都在web目录中将此行添加到
main()
fmt.Println(os.Getwd())
的开头。我想你会发现工作目录不是web目录。
package main

import (
    "fmt"
    "html/template"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        var data = map[string]string{
            "Name":    "john wick",
            "Message": "have a nice day",
        }

        var t, err = template.ParseFiles("template.html")
        if err != nil {
            fmt.Println(err.Error())
            return
        }

        t.Execute(w, data)
    })

    fmt.Println("starting web server at http://localhost:8080/")
    http.ListenAndServe(":8080", nil)
}