This README documents only the public API exported by the goserver package.
Short summary
serverprovides a specialized HTTP server handler for TinyWASM applications.- It operates in two modes:
- In-Memory (Default): Runs a lightweight
net/httpserver within the application process. Best for development speed and zero-file generation start. - External Process (Permanent): Generates a standalone main Go file, compiles it, and runs it as a separate process. Best for customization and production-like validation.
- In-Memory (Default): Runs a lightweight
- It seamlessly handles the transition between modes via
CreateTemplateServer.
Public API (types and functions)
-
type
Config- Fields:
AppRootDir stringSourceDir string(Default:"web")OutputDir string(Default:"web")PublicDir string(Default:"web/public")AppPort string(Default:"8080")Routes []func(mux *http.ServeMux)— Register HTTP handlers for In-Memory mode.ArgumentsForCompilingServer func() []stringArgumentsToRunServer func() []stringLogger func(message ...any)ExitChan chan bool
- Fields:
-
func
NewConfig() *Config— returns a new Config with default values. -
type
ServerHandler- Construct with:
New(c *Config) *ServerHandler - Startup Logic: Automatically detects if a server file exists in
SourceDir.- If exists: Starts in External Process mode.
- If missing: Starts in In-Memory mode using provided
Routes.
- Exported methods:
StartServer(wg *sync.WaitGroup)— Starts the server (async).CreateTemplateServer(progress chan<- string) error— Transitions from In-Memory to External mode. Generates files, compiles, and restarts.RestartServer() error— Restarts the server.NewFileEvent(...)— Handles hot-reloads (recompiles external server or no-op/refresh for in-memory).MainInputFileRelativePath() stringUnobservedFiles() []string
- Construct with:
Notes and behaviour
- Routes Registration: Use
Config.Routesto register handlers (e.g., static assets, API endpoints) so they work immediately in In-Memory mode. - Persistence: Once
CreateTemplateServeris called (or if files exist), the server remains in "External" mode permanently for that project unless files are deleted.
Minimal usage example
package main
import (
"fmt"
"net/http"
"os"
"sync"
"github.com/tinywasm/server"
)
func main() {
// Define a route function
myRoute := func(mux *http.ServeMux) {
mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello from In-Memory Server!")
})
}
cfg := &server.Config{
AppRootDir: ".",
Routes: []func(*http.ServeMux){myRoute},
Logger: func(messages ...any) { fmt.Fprintln(os.Stdout, messages...) },
}
handler := server.New(cfg)
var wg sync.WaitGroup
wg.Add(1)
go handler.StartServer(&wg)
wg.Wait()
// To switch to external mode later:
// handler.CreateTemplateServer(nil)
}