Home > Backend Development > Golang > How Can I Serve Static Files Embedded in a Go Binary?

How Can I Serve Static Files Embedded in a Go Binary?

Mary-Kate Olsen
Release: 2024-12-07 02:50:18
Original
195 people have browsed it

How Can I Serve Static Files Embedded in a Go Binary?

Serving Static Files from Binary in Go: A Custom FileSystem

When serving static files in Go, the FileServer handler simplifies the process. However, for cases where only a few static files need to be deployed, an alternative approach can eliminate the need for managing those files externally.

InMemoryFS Implementation

The FileServer requires a FileSystem object, leading to the question of how to bake static files into a binary. An implementation of InMemoryFS can serve files from memory, eliminating the need to interact with the file system directly.

package main

import (
    "io"
    "net/http"
    "time"
)

type InMemoryFS map[string]io.ReadCloser

// Implements FileSystem interface
func (fs InMemoryFS) Open(name string) (http.File, error) {
    f, ok := fs[name]
    if !ok {
        return nil, os.ErrNotExist
    }
    return &InMemoryFile{
        ReadCloser: f,
    }, nil
}

type InMemoryFile struct {
    io.ReadCloser
}

// Implements http.File interface
func (f *InMemoryFile) Close() error {
    return nil
}
func (f *InMemoryFile) Stat() (os.FileInfo, error) {
    fi, err := f.ReadCloser.Stat()
    if err != nil {
        return nil, err
    }
    return &InMemoryFileInfo{
        name: f.ReadCloser.(os.FileInfo).Name(),
        size: fi.Size(),
        modTime: fi.ModTime(),
    }, nil
}

type InMemoryFileInfo struct {
    name string
    size int64
    modTime time.Time
}

// Implements os.FileInfo
func (s *InMemoryFileInfo) Name() string       { return s.name }
func (s *InMemoryFileInfo) Size() int64        { return s.size }
func (s *InMemoryFileInfo) Mode() os.FileMode  { return 0644 }
func (s *InMemoryFileInfo) ModTime() time.Time { return s.modTime }
func (s *InMemoryFileInfo) IsDir() bool        { return false }
func (s *InMemoryFileInfo) Sys() interface{}   { return nil }
Copy after login

Example Usage

The InMemoryFS implementation can be utilized with the FileServer as follows:

func main() {
    FS := make(InMemoryFS)
    // Load static files into memory
    FS["foo.html"] = os.Open("foo.html")
    FS["bar.css"] = os.Open("bar.css")
    http.Handle("/", http.FileServer(FS))
    http.ListenAndServe(":8080", nil)
}
Copy after login

Alternative Considerations

Instead of creating a custom FileSystem, it might be simpler to rewrite the serving part to handle a small number of static files directly, avoiding the need to emulate a complete file system. Ultimately, the best approach depends on the specific requirements of the project.

The above is the detailed content of How Can I Serve Static Files Embedded in a Go Binary?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template