Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang return static html file at specified route

Tags:

go

gorilla

I am working on a simple todo app in go.

I have determined that all the pages except a user's list of todos can safely be a static html page. * Login form * new account form * index page that talks about the todo app

I see no reason currently for these to be go templates.

My question is how (within go, not using something like nginx) can I have a static html set to return at a specific route most efficiently?

For example index.html to be returned at "/"

I know I could do something like:

func GetNewAccount(res http.ResponseWriter, req *http.Request) {
        body, _ := ioutil.ReadFile("templates/register.html")
        fmt.Fprint(res, string(body))
}

or

var register, _ = string(ioutil.ReadFile("templates/register.html"))
func GetNewAccount(res http.ResponseWriter, req *http.Request) {
        fmt.Fprint(res, register)
}

To me these seems like more roundabout ways to do something seemingly simple.

like image 872
gaigepr Avatar asked Jun 29 '14 21:06

gaigepr


1 Answers

If all your static files under the same tree, you could use http.FileServer:

http.Handle("/s/", http.StripPrefix("/s/", http.FileServer(http.Dir("/path/to/static/files/"))))

Otherwise pre-loading the html files you want into a map in func init() then making one handler to fmt.Fprint them based on the request's path should work.

Example of a simple static file handler :

func StaticFilesHandler(path, prefix, suffix string) func(w http.ResponseWriter, req *http.Request) {
    files, err := filepath.Glob(filepath.Join(path, "*", suffix))
    if err != nil {
        panic(err)
    }
    m := make(map[string][]byte, len(files))
    for _, fn := range files {
        if data, err := ioutil.ReadFile(fn); err == nil {
            fn = strings.TrimPrefix(fn, path)
            fn = strings.TrimSuffix(fn, suffix)
            m[fn] = data
        } else {
            panic(err)
        }
    }
    return func(w http.ResponseWriter, req *http.Request) {
        path := strings.TrimPrefix(req.URL.Path, prefix)
        if data := m[path]; data != nil {
            fmt.Fprint(w, data)
        } else {
            http.NotFound(w, req)
        }
    }
}

then you can use it like :

http.Handle("/s/", StaticFilesHandler("/path/to/static/files", "/s/", ".html"))
like image 139
OneOfOne Avatar answered Nov 12 '22 02:11

OneOfOne