5
0
mirror of https://github.com/wailsapp/wails.git synced 2025-05-17 09:29:30 +08:00

Standardise and enhance fileserver service

This commit is contained in:
Fabio Massaioli 2025-02-05 14:29:44 +01:00
parent 2c85b109ac
commit 726084fa98

View File

@ -1,35 +1,29 @@
package fileserver package fileserver
import ( import (
"context"
"net/http" "net/http"
"sync/atomic"
"github.com/wailsapp/wails/v3/pkg/application"
) )
// ---------------- Service Setup ----------------
// This is the main Service struct. It can be named anything you like.
type Config struct { type Config struct {
// RootPath specifies the filesystem path from which requests are to be served.
RootPath string RootPath string
} }
type Service struct { type Service struct {
config *Config fs atomic.Pointer[http.Handler]
fs http.Handler
} }
func New(config *Config) *Service { // New initialises an unconfigured fileserver. See [Configure] for details.
return &Service{ func New() *Service {
config: config, return NewWithConfig(nil)
fs: http.FileServer(http.Dir(config.RootPath)),
}
} }
// ServiceShutdown is called when the app is shutting down // New initialises and optionally configures a fileserver. See [Service.Configure] for details.
// You can use this to clean up any resources you have allocated func NewWithConfig(config *Config) *Service {
func (s *Service) ServiceShutdown() error { result := &Service{}
return nil result.Configure(config)
return result
} }
// ServiceName returns the name of the plugin. // ServiceName returns the name of the plugin.
@ -38,14 +32,23 @@ func (s *Service) ServiceName() string {
return "github.com/wailsapp/wails/v3/services/fileserver" return "github.com/wailsapp/wails/v3/services/fileserver"
} }
// ServiceStartup is called when the app is starting up. You can use this to // Configure reconfigures the fileserver.
// initialise any resources you need. // If config is nil, then every request will receive a 503 Service Unavailable response.
func (s *Service) ServiceStartup(ctx context.Context, options application.ServiceOptions) error { //
// Any initialization code here //wails:ignore
return nil func (s *Service) Configure(config *Config) {
if config == nil {
s.fs.Store(&dummyHandler)
} else {
var fs http.Handler = http.FileServer(http.Dir(config.RootPath))
s.fs.Store(&fs)
}
} }
func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Create a new file server rooted at the given path (*s.fs.Load()).ServeHTTP(w, r)
s.fs.ServeHTTP(w, r)
} }
var dummyHandler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Fileserver service has not been configured yet", http.StatusServiceUnavailable)
})