Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GOLANG How can I load a certain html file from templates directory using http.FileServer

Tags:

http

go

mux

func main() {
    mux := http.NewServeMux()
    staticHandler := http.FileServer(http.Dir("./templates"))
    mux.Handle("/", http.StripPrefix("/", staticHandler))
    log.Fatal(http.ListenAndServe(":8080", mux))
}

I want to load a html file which is in 'templates' directory. if there are more than one files in 'templates', how can I select certain file to load?

like image 702
부건혁 Avatar asked Nov 27 '25 02:11

부건혁


1 Answers

You can use http.ServeFile() to build your own file server.

See sketch below.

Then you can intercept the served files within your custom fileHandler.ServeHTTP().

package main

import (
    "log"
    "net/http"
    "path"
    "path/filepath"
    "strings"
)

func main() {
    mux := http.NewServeMux()

    //staticHandler := http.FileServer(http.Dir("./templates"))
    staticHandler := fileServer("./templates")

    mux.Handle("/", http.StripPrefix("/", staticHandler))
    log.Printf("listening")
    log.Fatal(http.ListenAndServe(":8080", mux))
}

// returns custom file server
func fileServer(root string) http.Handler {
    return &fileHandler{root}
}

// custom file server
type fileHandler struct {
    root string
}

func (f *fileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    upath := r.URL.Path
    if !strings.HasPrefix(upath, "/") {
        upath = "/" + upath
        r.URL.Path = upath
    }
    name := filepath.Join(f.root, path.Clean(upath))
    log.Printf("fileHandler.ServeHTTP: path=%s", name)
    http.ServeFile(w, r, name)
}
like image 149
Everton Avatar answered Nov 29 '25 22:11

Everton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!