英文:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论