server

package module
v0.1.21 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 31, 2025 License: MIT Imports: 17 Imported by: 0

README

goserver

Project Badges

goserver

This README documents only the public API exported by the goserver package.

Short summary

  • server provides a specialized HTTP server handler for TinyWASM applications.
  • It operates in two modes:
    1. In-Memory (Default): Runs a lightweight net/http server within the application process. Best for development speed and zero-file generation start.
    2. 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.
  • It seamlessly handles the transition between modes via CreateTemplateServer.

Public API (types and functions)

  • type Config

    • Fields:
      • AppRootDir string
      • SourceDir 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() []string
      • ArgumentsToRunServer func() []string
      • Logger func(message ...any)
      • ExitChan chan bool
  • 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() string
      • UnobservedFiles() []string

Notes and behaviour

  • Routes Registration: Use Config.Routes to register handlers (e.g., static assets, API endpoints) so they work immediately in In-Memory mode.
  • Persistence: Once CreateTemplateServer is 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)
}

Contributing

Documentation

Index

Constants

View Source
const StoreKeyExternalServer = "server_external_mode"

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	AppRootDir                  string                 // e.g., /home/user/project (application root directory)
	SourceDir                   string                 // directory location of main.go e.g., src/cmd/appserver (relative to AppRootDir)
	OutputDir                   string                 // compilation and execution directory e.g., deploy/appserver (relative to AppRootDir)
	PublicDir                   string                 // default public dir for generated server (e.g., src/web/public)
	MainInputFile               string                 // main input file name (default: "main.go", can be "server.go", etc.)
	ArgumentsForCompilingServer func() []string        // e.g., []string{"-X 'main.version=v1.0.0'"}
	ArgumentsToRunServer        func() []string        // e.g., []string{"dev"}
	AppPort                     string                 // e.g., 8080
	Routes                      []func(*http.ServeMux) // Functions to register routes on the HTTP server
	ExitChan                    chan bool              // Global channel to signal shutdown
}

func NewConfig

func NewConfig() *Config

NewConfig provides a default configuration.

type ServerHandler

type ServerHandler struct {
	*Config
	// contains filtered or unexported fields
}

func New

func New(c *Config) *ServerHandler

func (*ServerHandler) CreateTemplateServer added in v0.1.16

func (h *ServerHandler) CreateTemplateServer(progress chan<- string) error

CreateTemplateServer switches from In-Memory to External mode. It generates the server files (if not present), compiles, and runs them. This implements the transition from "In-Memory" to "Permanent" (External) mode.

func (*ServerHandler) Logger added in v0.1.21

func (h *ServerHandler) Logger(messages ...any)

func (*ServerHandler) MainInputFileRelativePath

func (h *ServerHandler) MainInputFileRelativePath() string

MainInputFileRelativePath returns the path relative to AppRootDir (e.g., "src/cmd/appserver/main.go")

func (*ServerHandler) Name added in v0.1.21

func (h *ServerHandler) Name() string

func (*ServerHandler) NewFileEvent

func (h *ServerHandler) NewFileEvent(fileName, extension, filePath, event string) error

event: create,write,remove,rename

func (*ServerHandler) RestartServer

func (h *ServerHandler) RestartServer() error

func (*ServerHandler) SetBuildOnDisk added in v0.1.19

func (h *ServerHandler) SetBuildOnDisk(onDisk bool)

SetBuildOnDisk sets whether the server artifacts should be written to disk.

func (*ServerHandler) SetExternalServerMode added in v0.1.19

func (h *ServerHandler) SetExternalServerMode(external bool)

SetExternalServerMode switches between Internal and External server strategies.

func (*ServerHandler) SetLog added in v0.1.21

func (h *ServerHandler) SetLog(f func(message ...any))

func (*ServerHandler) StartServer

func (h *ServerHandler) StartServer(wg *sync.WaitGroup)

Start initiates the server using the current strategy (In-Memory or External)

func (*ServerHandler) SupportedExtensions

func (h *ServerHandler) SupportedExtensions() []string

func (*ServerHandler) UnobservedFiles

func (h *ServerHandler) UnobservedFiles() []string

UnobservedFiles returns the list of files that should not be tracked by file watchers

type ServerModeHandler added in v0.1.19

type ServerModeHandler struct {
	// contains filtered or unexported fields
}

func NewServerModeHandler added in v0.1.19

func NewServerModeHandler(h *ServerHandler, db Store, ui UI) *ServerModeHandler

func (*ServerModeHandler) Execute added in v0.1.19

func (s *ServerModeHandler) Execute()

func (*ServerModeHandler) Label added in v0.1.19

func (s *ServerModeHandler) Label() string

func (*ServerModeHandler) Name added in v0.1.19

func (s *ServerModeHandler) Name() string

func (*ServerModeHandler) SetLog added in v0.1.21

func (s *ServerModeHandler) SetLog(f func(message ...any))

type ServerStrategy added in v0.1.16

type ServerStrategy interface {
	Start(wg *sync.WaitGroup) error
	Stop() error
	Restart() error
	HandleFileEvent(fileName, extension, filePath, event string) error
	Name() string
}

type Store added in v0.1.19

type Store interface {
	Get(key string) (string, error)
	Set(key, value string) error
}

Store defines the minimal interface for persistent storage

type UI added in v0.1.19

type UI interface {
	RefreshUI()
}

UI defines the minimal interface for UI interaction

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL