Good morning everyone,
I’m trying to create a basic go server with go notation.
Here is the project architecture :
-
gohtml
---- index.gohtml
---- about.gohtml -
templates
---- layout.gohtml
server.go
And here is the code for each file :
index.gohtml
{{define "page_title"}} Welcome Page {{ end }}
{{define "page_body"}}
<p>Welcome on home page !</p>
{{end}}
about.gohtml
{{define "page_title"}} About Page {{ end }}
{{define "page_body"}}
<p>Welcome on about page !</p>
{{end}}
layout.gohtml
{{define "layout}}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{template "page_title"}}</title>
</head>
<body>
{{template "page_body"}}
</body>
</html>
{{end}}
server.go
package main
import (
"net/http"
"html/template"
"path/filepath"
"log"
)
func main(){
// Handle client's requests to templates system
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){
// Manage template's layout path
layout_path := filepath.Join("templates","layout.gohtml")
// Manage *http.request
request_path := filepath.Join("gohtml",filepath.Clean(r.URL.Path))
// Parse layout and client's request files
template_page, err := template.ParseFiles(request_path, layout_path)
if err != nil{
log.Println("Error : Failed to parse files")
log.Fatal(err)
}
// Execute template on http.ResponseWriter
template_page.ExecuteTemplate(w, "layout", nil)
})
// Start server
// Error handling OK
log.Fatal(http.ListenAndServe(":8080", nil))
}
When I run my server.go file I get :
2020/03/31 11:44:58 Error : Failed to parse files
2020/03/31 11:44:58 read gohtml: Bad file descriptor
exit status 1
Thank you in advance for your help