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 execution modes:
- Internal (Default): Runs a lightweight
net/httpserver within the application process. Best for development speed and zero-file generation start. - External: Generates a standalone main Go file, compiles it, and runs it as a separate process. Best for customization and production-like validation.
- Internal (Default): Runs a lightweight
- It also supports two compilation modes: In-Memory (default) and On-Disk.
- It seamlessly handles the transition between execution modes via
SetExternalServerMode.
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 Internal 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 - Exported methods:
StartServer(wg *sync.WaitGroup)— Starts the server (async).SetExternalServerMode(external bool) error— Switches between Internal and External execution modes. When switching to External, it generates files (if missing), compiles, and starts the process.CreateTemplateServer() error— Legacy method specifically for transitioning from Internal to External mode.SetCompilationOnDisk(onDisk bool)— Switches between In-Memory and On-Disk compilation artifacts.RestartServer() error— Restarts the server.NewFileEvent(...)— Handles hot-reloads (recompiles external server or no-op/refresh for internal).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 Internal mode. - Port Management: When switching modes, the handler automatically waits for the port to be free before starting the new strategy.
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 Internal 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.SetExternalServerMode(true)
}