Home > Mobile >  How to serve file from go embed
How to serve file from go embed

Time:11-23

I have a static directory, containing a sign.html file :

//go:embed static
var static embed.FS

It is served that way and works fine :

fSys, err := fs.Sub(static, "static")
if err != nil {
    return err
}
mux.Handle("/", http.FileServer(http.FS(fSys)))

On some routes though (for instance: /sign), I want to do some checks before serving the page. This is my handler :

func (h Handler) ServeSignPage(w http.ResponseWriter, r *http.Request) error {
    publicKey := r.URL.Query().Get("publicKey")
    err := h.Service.AuthorizeClientSigning(r.Context(), publicKey)
    if err != nil {
        return err
    }
    // this is where I'd like to serve the embed file
    // sign.html from the static directory
    http.ServeFile(w, r, "sign.html")
    return nil
}

Unfortunately, the ServeFile displays not found. How can I serve the file from the file server within that ServeSignPage ?

CodePudding user response:

Option 1

Read the file to a slice of bytes. Write the bytes to the response.

p, err := static.ReadFile("static/sign.html")
if err != nil {
    // TODO: Handle error as appropriate for the application.
}
w.Write(p)

Option 2

If the path for the ServeSignPage handler is the same as the static file in the file server, then delegate to the file server.

Store the file server in a package-level variable.

var staticServer http.Handler

func init() {
    fSys, err := fs.Sub(static, "static")
    if err != nil {
          panic(err)
    }
    staticServer = http.FileServer(http.FS(fSys)))
}

Use the static server as the handler:

 mux.Handle("/", staticServer)

Delegate to the static server in ServeSignPage:

func (h Handler) ServeSignPage(w http.ResponseWriter, r *http.Request) error {
    publicKey := r.URL.Query().Get("publicKey")
    err := h.Service.AuthorizeClientSigning(r.Context(), publicKey)
    if err != nil {
        return err
    }
    staticServer.ServeHTTP(w, r)
    return nil
}
  •  Tags:  
  • go
  • Related