恐慌:打开模板/layout-main-page.html时出错:系统找不到指定的路径

huangapple go评论87阅读模式
英文:

panic: open template/layout-main-page.html: The system cannot find the path specified

问题

我是你的中文翻译助手,以下是翻译好的内容:

我是Golang的新手,我正在尝试在我的应用程序中运行一个简单的测试,但每次都会出现panic错误。我找不到问题出在哪里。

我已经在多个地方查找了,但找不到解决方案。

如果你对代码有任何问题,随时问我。

错误信息:

PS D:\projetos go\api-ranking-crypto> go test ./test/
panic: open template/layout-main-page.html: The system cannot find the path specified.

goroutine 1 [running]:
html/template.Must(...)
        D:/Go/src/html/template/template.go:374
github.com/maickmachado/upvote-api/controllers.init()
        D:/projetos go/api-ranking-crypto/controllers/controllers.go:15 +0x1d8
FAIL    github.com/maickmachado/upvote-api/test 0.209s
FAIL

我的测试代码:

    func TestHealthCheck(t *testing.T) {
	tt := []struct {
		name   string
		method string
		statusCode int
	}{
		{
			name:   "status ok",
			method: http.MethodGet,
			statusCode: http.StatusOK,
		},
	}
	for _, tc := range tt {
		t.Run(tc.name, func(t *testing.T) {
			request := httptest.NewRequest(tc.method, "/healthcheck", nil)
			responseRecorder := httptest.NewRecorder()

			controllers.HealthCheck(responseRecorder, request)

			if responseRecorder.Code != tc.statusCode {
				t.Errorf("Want status '%d', got '%d'", tc.statusCode, responseRecorder.Code)
			}
		})
	}
}

控制器文件:

var (
	TmplMainPage   = template.Must(template.ParseFiles("template/layout-main-page.html"))
	TmplDetailPage = template.Must(template.ParseFiles("template/layout-detail-page.html"))
	TmplError      = template.Must(template.ParseFiles("template/layout-erro.html"))
	TmplRanking    = template.Must(template.ParseFiles("template/layout-ranking.html"))
)

func GetAllData(w http.ResponseWriter, r *http.Request) {...}

func GetRanking(w http.ResponseWriter, r *http.Request) {...}

func CryptoDetail(w http.ResponseWriter, r *http.Request) {...}

func VoteCrypto(w http.ResponseWriter, r *http.Request) {...}

func HealthCheck(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", "application/json")
	io.WriteString(w, `{"alive": true}`)}

我的主文件:

func init() {
	database.CreateMongoBD()
}

func main() {
	routes.HandleRequest()
}

我的路由文件:

func HandleRequest() {
	myRouter := mux.NewRouter().StrictSlash(true)
	myRouter.HandleFunc("/cryptocoins", controllers.GetAllData).Methods("GET")
	myRouter.HandleFunc("/ranking", controllers.GetRanking).Methods("GET")
	myRouter.HandleFunc("/cryptocoins/{name}", controllers.CryptoDetail).Methods("GET")
	myRouter.HandleFunc("/healthcheck", controllers.HealthCheck).Methods("GET")
	myRouter.HandleFunc("/cryptocoins/vote/{text}", controllers.VoteCrypto).Methods("POST")
	myRouter.NotFoundHandler = http.Handler(http.HandlerFunc(controllers.ErrorHandler404))

	log.Fatal(http.ListenAndServe(":8080", myRouter))
}
英文:

I'm new in Golang and I'm trying to run a simple test in my application but a panic occurs everytime. I can't find what is the problem.

I've looked in several places but couldn't find a solution.

Feel free to ask me anything about the code, if you have any questions, just ask.

The error mensage:

PS D:\projetos go\api-ranking-crypto> go test ./test/
panic: open template/layout-main-page.html: The system cannot find the path specified.

goroutine 1 [running]:
html/template.Must(...)
        D:/Go/src/html/template/template.go:374
github.com/maickmachado/upvote-api/controllers.init()
        D:/projetos go/api-ranking-crypto/controllers/controllers.go:15 +0x1d8
FAIL    github.com/maickmachado/upvote-api/test 0.209s
FAIL

My test code:

    func TestHealthCheck(t *testing.T) {
	tt := []struct {
		name   string
		method string
		statusCode int
	}{
		{
			name:   "status ok",
			method: http.MethodGet,
			statusCode: http.StatusOK,
		},
	}
	for _, tc := range tt {
		t.Run(tc.name, func(t *testing.T) {
			request := httptest.NewRequest(tc.method, "/healthcheck", nil)
			responseRecorder := httptest.NewRecorder()

			controllers.HealthCheck(responseRecorder, request)

			if responseRecorder.Code != tc.statusCode {
				t.Errorf("Want status '%d', got '%d'", tc.statusCode, responseRecorder.Code)
			}
		})
	}
}

The controller file:

var (
	TmplMainPage   = template.Must(template.ParseFiles("template/layout-main-page.html"))
	TmplDetailPage = template.Must(template.ParseFiles("template/layout-detail-page.html"))
	TmplError      = template.Must(template.ParseFiles("template/layout-erro.html"))
	TmplRanking    = template.Must(template.ParseFiles("template/layout-ranking.html"))
)

func GetAllData(w http.ResponseWriter, r *http.Request) {...}

func GetRanking(w http.ResponseWriter, r *http.Request) {...}

func CryptoDetail(w http.ResponseWriter, r *http.Request) {...}

func VoteCrypto(w http.ResponseWriter, r *http.Request) {...}

func HealthCheck(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", "application/json")
	io.WriteString(w, `{"alive": true}`)}

My main file:

func init() {
	database.CreateMongoBD()
}

func main() {
	routes.HandleRequest()
}

My route file:

func HandleRequest() {
	myRouter := mux.NewRouter().StrictSlash(true)
	myRouter.HandleFunc("/cryptocoins", controllers.GetAllData).Methods("GET")
	myRouter.HandleFunc("/ranking", controllers.GetRanking).Methods("GET")
	myRouter.HandleFunc("/cryptocoins/{name}", controllers.CryptoDetail).Methods("GET")
	myRouter.HandleFunc("/healthcheck", controllers.HealthCheck).Methods("GET")
	myRouter.HandleFunc("/cryptocoins/vote/{text}", controllers.VoteCrypto).Methods("POST")
	myRouter.NotFoundHandler = http.Handler(http.HandlerFunc(controllers.ErrorHandler404))

	log.Fatal(http.ListenAndServe(":8080", myRouter))
}

答案1

得分: 0

感谢Cerise Limón在另一篇帖子中的回答。

我做了一些更改。

将模板放在Handle函数内部,并将template.Must从其中移除:

func ErrorHandler404(w http.ResponseWriter, r *http.Request) {

	TmplError, _ := template.ParseFiles("./template/layout-erro.html")

	w.WriteHeader(http.StatusNotFound)
	data := models.DetailPageData{
		PageTitle: "Erro 404 - Not Found",
	}
	err := TmplError.Execute(w, data)
	if err != nil {
		log.Println(err)
	}
}
英文:

Thanks to Cerise Limón and her answer in another post.

I changed some things.

Put the template inside the Handle function and take out the template.Must from it:

func ErrorHandler404(w http.ResponseWriter, r *http.Request) {

	TmplError, _ := template.ParseFiles("./template/layout-erro.html")

	w.WriteHeader(http.StatusNotFound)
	data := models.DetailPageData{
		PageTitle: "Erro 404 - Not Found",
	}
	err := TmplError.Execute(w, data)
	if err != nil {
		log.Println(err)
	}
}

huangapple
  • 本文由 发表于 2022年10月7日 08:55:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/73981315.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定