Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No such file or directory error in golang

Tags:

go

I want to specify an html template in one of my golang controller My directory structure is like this

 Project
 -com
  -src
   - controller
     -contoller.go
 -view
  - html
   -first.html

I want to load first.html for request /new .I have used NewHandler for url /new and the NewHandler func is executing when /new request comes and is in controller.go. Here is my code

func NewHandler(w http.ResponseWriter, r *http.Request) {
    t, err := template.ParseFiles("view/html/first.html")
    if err == nil {
        log.Println("Template parsed successfully....")
    }
 err := templates.ExecuteTemplate(w, "view/html/first.html", nil)
if err != nil {
    log.Println("Not Found template")
}
//  t.Execute(w, "")
}

But I am getting an error

     panic: open first.html: no such file or directory

Please help me to remove this error. Thanks in advance

like image 620
Akhil Sudhakaran Avatar asked Jul 07 '16 06:07

Akhil Sudhakaran


1 Answers

I have solved the issue by giving absolute path of the html. For that I created a class in which the html are parsed

package htmltemplates

import (
"html/template"
"path/filepath"
)

And in the NewHandler method I removed //Templates is used to store all Templates var Templates *template.Template

func init() {
filePrefix, _ := filepath.Abs("./work/src/Project/view/html/")       // path from the working directory
Templates = template.Must(template.ParseFiles(filePrefix + "/first.html")) 
...
//htmls must be specified here to parse it
}

And in the NewHandler I removed first 5 lines and instead gave

err := htmltemplates.Templates.ExecuteTemplate(w, "first.html", nil)

It is now working .But need a better solution if any

like image 192
Akhil Sudhakaran Avatar answered Sep 20 '22 02:09

Akhil Sudhakaran