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, routed viahttpd.NewRouter. 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. - The
httpdsubpackage (github.com/tinywasm/server/httpd) is the batteries-includedrouter.Routeradapter used internally and available for production use (see below).
Public API (types and functions)
-
func
New() *ServerHandler— creates a handler with defaultConfig(AppRootDir: ".",SourceDir/OutputDir: "web",AppPort: "6060"). Configure it with the setters below (fluent methods return*ServerHandlerwhere noted). -
type
ServerHandler- Setters:
SetAppRootDir(dir string)SetSourceDir(dir string)SetOutputDir(dir string)SetPublicDir(dir string) *ServerHandlerSetMainInputFile(name string)SetPort(port string)/Port() stringSetHTTPS(enabled bool) *ServerHandlerSetLogger(fn func(...any)) *ServerHandlerSetExitChan(ch chan bool) *ServerHandlerSetOpenBrowser(fn func(port string, https bool)) *ServerHandlerSetStore(s Store) *ServerHandlerSetUI(ui UI) *ServerHandlerSetBeforeExternalServerStart(fn func() error) *ServerHandler— hook invoked synchronously before every external-mode start.SetGitIgnoreAdd(fn func(string) error) *ServerHandlerSetCompileArgs(fn func() []string)SetRunArgs(fn func() []string)SetDisableGlobalCleanup(disable bool)
- Routing:
RegisterRoutes(fn func(router.Router))— appends a route-registration callback (usinggithub.com/tinywasm/router'sRoutercontract). Call beforeStartServer. Used by both Internal and External modes.
- Lifecycle:
StartServer(wg *sync.WaitGroup)— starts the server (async).StopServer() errorRestartServer() errorSetExternalServerMode(external bool) error— switches between Internal and External execution modes. When switching to External, it generates files (if missing), compiles, and starts the process. Cannot switch back to Internal.NewFileEvent(fileName, extension, filePath, event string) error— handles hot-reloads (recompiles external server or no-op for internal).MainInputFileRelativePath() stringUnobservedFiles() []string
- Setters:
Notes and behaviour
- Routes Registration: Use
RegisterRoutesto register handlers via therouter.Routercontract (e.g.,r.Get("/path", handler)) so they work immediately in Internal mode and are carried over to External 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"
"os"
"sync"
"github.com/tinywasm/router"
"github.com/tinywasm/server"
)
func main() {
handler := server.New()
handler.SetAppRootDir(".")
handler.SetLogger(func(messages ...any) { fmt.Fprintln(os.Stdout, messages...) })
handler.RegisterRoutes(func(r router.Router) {
r.Get("/hello", func(ctx router.Context) {
fmt.Fprint(ctx, "Hello from Internal Server!")
})
})
var wg sync.WaitGroup
wg.Add(1)
go handler.StartServer(&wg)
wg.Wait()
// To switch to external mode later:
// handler.SetExternalServerMode(true)
}github.com/tinywasm/server/httpd implements router.Router/router.Context on top of
net/http, with production batteries built in: gzip, no-cache headers, static file
serving, TLS (AutoCert/custom cert/DevTLS), a /health endpoint, an optional /_routes
JSON listing, and closed-by-default RBAC enforcement (Config.Authn for global identity,
Config.Authorize for per-route Requires(resource, action) checks; routes must opt into
Public() to allow anonymous access).
s := httpd.New(httpd.Config{
Port: "8080",
Health: true,
})
s.Mount(myAPIModule) // github.com/tinywasm/router.APIModule
if err := s.ListenAndServe(); err != nil {
log.Fatal(err)
}Handler() returns the fully wired http.Handler (static files, batteries, routes, RBAC)
without opening a port, for use with httptest. See docs/ARCHITECTURE.md
for design details.