Documentation
¶
Index ¶
- Constants
- Variables
- func OptimizedAssetPath(view string) string
- func RegisterEmbeddedAssetsFS(assets fs.FS)
- func RenderTemplate(assetStorage *AssetStorage, templatePath string, layoutPath string, ...) (string, error)
- type APIResponse
- type ApiRoute
- type AssetStorage
- type Cookie
- type Engine
- type PageRoute
- type Request
- type SameSiteMode
- type SecurityLayer
- type Server
- func (s *Server) Api(route ApiRoute)
- func (s *Server) AssetOptimizationEnabled() bool
- func (s *Server) AssetStorage() *AssetStorage
- func (s *Server) Page(route PageRoute)
- func (s *Server) ResolvePageScriptAssets(route *PageRoute, compiledViews map[string]string) (string, string)
- func (s *Server) ResolvePageTemplatePaths(route *PageRoute) (string, string)
- func (s *Server) Security(layer SecurityLayer)
- func (s *Server) Serve(port int) error
- func (s *Server) SetAssetOptimization(enabled bool)
- func (s *Server) SetDefaultLayout(path string)
- func (s *Server) StaticAlias(urlPath string, staticPath string)
- func (s *Server) WebSocket(route WebSocketRoute) *WebSocketHub
- type WebSocketConn
- func (c *WebSocketConn) Close() error
- func (c *WebSocketConn) Done() <-chan struct{}
- func (c *WebSocketConn) Outbound() <-chan WebSocketFrame
- func (c *WebSocketConn) Request() *Request
- func (c *WebSocketConn) Send(message []byte) error
- func (c *WebSocketConn) SendJSON(v any) error
- func (c *WebSocketConn) SendText(message string) error
- type WebSocketFrame
- type WebSocketHub
- func (h *WebSocketHub) Broadcast(message []byte)
- func (h *WebSocketHub) BroadcastJSON(v any) error
- func (h *WebSocketHub) BroadcastText(message string)
- func (h *WebSocketHub) ConnectionCount() int
- func (h *WebSocketHub) Publish(topic string, message []byte)
- func (h *WebSocketHub) PublishJSON(topic string, v any) error
- func (h *WebSocketHub) PublishText(topic string, message string)
- func (h *WebSocketHub) Register(conn *WebSocketConn)
- func (h *WebSocketHub) Subscribe(conn *WebSocketConn, topic string)
- func (h *WebSocketHub) Unregister(conn *WebSocketConn)
- func (h *WebSocketHub) Unsubscribe(conn *WebSocketConn, topic string)
- type WebSocketRoute
Constants ¶
const DevWebSocketPort = 35729
DevWebSocketPort is the fixed port the bungo CLI listens on for live reload; must match injected client.
Variables ¶
var ErrWebSocketClosed = errors.New("BunGo WebSocket Error: connection is closed")
ErrWebSocketClosed is returned by a connection's Send methods once it is closed, including after it was closed for failing to keep up with its outbound buffer.
Functions ¶
func OptimizedAssetPath ¶ added in v0.3.0
OptimizedAssetPath converts a route view path into the optimized `/_bungo/*.js` route. Inputs: - view: page route view path relative to `views/`. Outputs: - string: optimized JavaScript asset route path.
func RegisterEmbeddedAssetsFS ¶ added in v0.3.0
RegisterEmbeddedAssetsFS registers a process-wide embedded asset filesystem used by BunGo servers. Inputs: - assets: filesystem containing project files generated by `bungo build` embedding. Outputs: - none
func RenderTemplate ¶
func RenderTemplate( assetStorage *AssetStorage, templatePath string, layoutPath string, inlineJS string, moduleSrc string, data map[string]any, ) (string, error)
RenderTemplate renders a page template, optionally composed inside a layout template. Inputs: - assetStorage: server asset storage used to resolve template/layout files. - templatePath: required web-root-relative path to the page-specific .gohtml template file. - layoutPath: optional web-root-relative wrapper .gohtml path defining {{block "content" .}}. - inlineJS: compiled JavaScript source to inject inline as a module script. - moduleSrc: optional static module URL injected when asset optimization is enabled. - data: template data passed to Execute after BunGo script fields are merged in. Outputs: - string: fully rendered HTML with BunGo data/scripts injected into template output. - error: non-nil when template files cannot be read, parsed, or executed.
Types ¶
type APIResponse ¶
type APIResponse struct {
StatusCode int
Body any
Cookies []Cookie // Optional Set-Cookie headers emitted with the response
}
APIResponse represents an API response
type ApiRoute ¶
type ApiRoute struct {
Path string
Version string
Method string
SecurityLayer []string
Handler func(req *Request) (APIResponse, error)
}
ApiRoute represents a configuration for an API route.
Method must be a standard HTTP verb (GET, HEAD, POST, PUT, PATCH, DELETE, CONNECT, OPTIONS, TRACE). Registration normalizes it to uppercase; invalid or empty values panic at Api registration time.
type AssetStorage ¶ added in v0.3.0
type AssetStorage struct {
// contains filtered or unexported fields
}
AssetStorage provides a unified web asset reader with memory-first and disk-fallback lookups.
func (*AssetStorage) Exists ¶ added in v0.3.0
func (s *AssetStorage) Exists(relativePath string) bool
Exists reports whether a relative web asset path exists in memory or on disk. Inputs: - relativePath: slash-style path relative to web root, or empty string for the web root itself. Outputs: - bool: true when the asset exists in embedded memory or disk storage.
func (*AssetStorage) PrepareWebDirForBuild ¶ added in v0.3.0
func (s *AssetStorage) PrepareWebDirForBuild() (string, func(), error)
PrepareWebDirForBuild returns a disk directory suitable for esbuild and a cleanup callback. Inputs: - none Outputs: - string: filesystem directory containing a materialized `layouts`, `views`, and optional `static`. - func(): cleanup callback that removes temporary materialized assets when invoked. - error: non-nil when temporary directory creation or embedded asset extraction fails.
func (*AssetStorage) ReadFile ¶ added in v0.3.0
func (s *AssetStorage) ReadFile(relativePath string) ([]byte, error)
ReadFile reads one relative web asset path preferring memory and then falling back to disk. Inputs: - relativePath: slash-style path relative to web root. Outputs: - []byte: file contents for the resolved asset path. - error: non-nil when the asset is invalid or missing in both memory and disk stores.
func (*AssetStorage) ReadStaticFile ¶ added in v0.3.0
func (s *AssetStorage) ReadStaticFile(requestPath string) ([]byte, error)
ReadStaticFile reads a static asset by URL-relative path and enforces path traversal safety. Inputs: - requestPath: URL-relative path under `/static/`, for example `css/app.css`. Outputs: - []byte: resolved static file bytes from memory-first, disk-fallback storage. - error: non-nil when requestPath is invalid or the static file is not found.
type Cookie ¶ added in v0.4.0
type Cookie struct {
Name string
Value string
Path string
Domain string
Expires time.Time
MaxAge int
Secure bool
HttpOnly bool
SameSite SameSiteMode
}
Cookie describes a Set-Cookie header in an engine-agnostic way.
Name is required. To delete a cookie on the client, set MaxAge to a negative value — engines translate this to Max-Age=0 plus an expired Expires date.
MaxAge semantics match net/http.Cookie:
- 0 — no Max-Age attribute is emitted
- >0 — Max-Age in seconds
- <0 — instructs the user agent to discard the cookie immediately
This struct intentionally has no transport-specific methods. Each engine supplies its own cookie converter (see Engine implementations) so the core package remains free of net/http or vendor SDK dependencies.
type Engine ¶
Invoker represents the execution environment starting the server. We define it locally to avoid import cycle, since engine pkg depends on bungo
type PageRoute ¶
type PageRoute struct {
Path string
Template string
Layout string
View string
SecurityLayer []string
Handler func(req *Request) (map[string]any, error)
}
PageRoute configures a single page route.
Template is required: the page-specific .gohtml file in layouts/ that holds the page content (and optionally {{define "content"}} when using a Layout).
Layout is optional: a wrapper .gohtml in layouts/ that defines {{block "content" .}}. When set, the Template is rendered inside that block, so you avoid repeating <html>, <head>, and <body> in every template. If empty, the Template is rendered as a standalone page.
View is optional: the corresponding .jsx/.tsx (or .js/.ts) entry in views/ to be compiled and injected into the page as a module script.
type Request ¶
type Request struct {
Context context.Context
Headers map[string]string
Params map[string]string // URL and Query parameters
Body []byte
Internal map[string]any // For passing context between Security Layers and Handlers
}
Request represents a framework-agnostic HTTP request
type SameSiteMode ¶ added in v0.4.0
type SameSiteMode string
SameSiteMode controls the SameSite attribute on a Cookie. An empty value omits the attribute and lets the user agent apply its default.
const ( SameSiteDefault SameSiteMode = "" SameSiteLax SameSiteMode = "Lax" SameSiteStrict SameSiteMode = "Strict" SameSiteNone SameSiteMode = "None" )
type SecurityLayer ¶
SecurityLayer represents a reusable security layer that can be applied to routes.
type Server ¶
type Server struct {
Pages map[string]PageRoute
APIs map[string]ApiRoute
WebSockets map[string]WebSocketRoute
SecurityLayers map[string]SecurityLayer
StaticAliases map[string]string // root URL path -> file path relative to webDir/static
Engine Engine
WebDir string
DefaultLayout string
// contains filtered or unexported fields
}
Server is the central registry for the BunGo application.
func NewServer ¶
NewServer creates a Server and validates required web directory structure at startup. Inputs: - engine: runtime engine implementation responsible for serving incoming requests. - webDir: base web directory containing required layouts/ and views/ subdirectories. Outputs: - *Server: initialized server registry with empty route and security maps.
func (*Server) Api ¶
Api registers an API route in the server route registry. Inputs: - route: API route configuration keyed by version, method, and path. Outputs: - none
func (*Server) AssetOptimizationEnabled ¶ added in v0.2.0
AssetOptimizationEnabled reports whether static module bundle delivery is enabled. Inputs: - none Outputs: - bool: true when SetAssetOptimization enabled external /_bungo bundle serving.
func (*Server) AssetStorage ¶ added in v0.3.0
func (s *Server) AssetStorage() *AssetStorage
AssetStorage returns the server storage abstraction for memory-first and disk-fallback web asset access. Inputs: - none Outputs: - *AssetStorage: server asset storage used by engines, template rendering, and builders.
func (*Server) Page ¶
Page registers a page route and validates referenced template, layout, and view files. Inputs: - route: page route configuration to store in the server route registry. Outputs: - none
func (*Server) ResolvePageScriptAssets ¶ added in v0.3.0
func (s *Server) ResolvePageScriptAssets(route *PageRoute, compiledViews map[string]string) (string, string)
ResolvePageScriptAssets resolves inline/module script values for one page route render. Inputs: - route: page route whose optional view determines script asset injection values. - compiledViews: map of compiled view source keyed by original route View value. Outputs: - string: inline JavaScript payload when asset optimization is disabled. - string: module source URL when asset optimization is enabled.
func (*Server) ResolvePageTemplatePaths ¶ added in v0.3.0
ResolvePageTemplatePaths returns template and layout asset paths relative to the configured web root. Inputs: - route: page route whose template and optional layout should be resolved. Outputs: - string: required template asset path relative to web root. - string: optional layout asset path relative to web root, or empty when no layout applies.
func (*Server) Security ¶
func (s *Server) Security(layer SecurityLayer)
Security registers a named security layer in the server security registry. Inputs: - layer: reusable security layer definition with name and handler function. Outputs: - none
func (*Server) Serve ¶
Serve starts server execution on the provided port using the configured engine. Inputs: - port: TCP port number used to build the engine listen address. Outputs: - error: non-nil when the engine fails to start or returns a runtime error.
func (*Server) SetAssetOptimization ¶ added in v0.2.0
SetAssetOptimization toggles static module delivery for compiled page view bundles. Inputs: - enabled: true to serve view bundles via /_bungo/*.js, false to inline module code. Outputs: - none
func (*Server) SetDefaultLayout ¶
SetDefaultLayout sets the default layout file used when a page route omits Layout. Inputs: - path: layout filename in webDir/layouts, or empty string to clear the default. Outputs: - none
func (*Server) StaticAlias ¶ added in v0.5.0
StaticAlias publishes one file from webDir/static at an additional root URL path. The alias URL must carry the same file extension as the target static file, so a URL never misrepresents the content type it serves (e.g. "/robots.txt" may only map onto a ".txt" file). Registration is fail-fast: the target file must already exist in the static directory. Inputs: - urlPath: absolute URL path to publish, for example "/robots.txt" or "/sitemap.xml". - staticPath: target file path relative to webDir/static, for example "robots.txt" or "seo/sitemap.xml". Outputs: - none
func (*Server) WebSocket ¶ added in v0.5.0
func (s *Server) WebSocket(route WebSocketRoute) *WebSocketHub
WebSocket registers a WebSocket route and returns the hub that fans messages out to its connections. The returned hub is the only handle to the route's hub — hold onto it (capture it in a closure, or store it) wherever you need to broadcast or publish; there is no lookup-a-hub-by-path accessor to fat-finger. Inputs: - route: WebSocket route configuration with path, security layers, and lifecycle callbacks. Outputs: - *WebSocketHub: hub bound to the route, usable from any handler or goroutine to broadcast or publish.
type WebSocketConn ¶ added in v0.5.0
type WebSocketConn struct {
// contains filtered or unexported fields
}
WebSocketConn is one connected client on a WebSocket route.
A connection is a concurrency-safe mailbox: Send* enqueue onto a buffered outbound channel drained by the transport's single writer goroutine, so handlers, hub broadcasts, and background goroutines can all send without coordination. Send* never block; a connection whose buffer stays full is closed as a slow consumer, and its Send* calls return ErrWebSocketClosed from then on.
Request returns the upgrade-time request, including the Internal map populated by the route's security layers — the idiomatic place to read the authenticated identity a layer stored during the handshake.
Engines create connections with NewWebSocketConn and drive their I/O through the Outbound and Done channels; application code only calls Request, Send*, and Close.
func NewWebSocketConn ¶ added in v0.5.0
func NewWebSocketConn(request *Request) *WebSocketConn
NewWebSocketConn creates a connection around an upgrade-time request; engines call it after a successful upgrade. It is part of the engine-facing seam, not the application API. Inputs: - request: request translated from the WebSocket handshake, carrying any Internal values set by security layers. Outputs: - *WebSocketConn: connection with an empty outbound buffer, ready to register in a hub.
func (*WebSocketConn) Close ¶ added in v0.5.0
func (c *WebSocketConn) Close() error
Close marks the connection closed, prompting a close frame and teardown; it is idempotent. Inputs: - none Outputs: - error: always nil; kept for symmetry with io closers.
func (*WebSocketConn) Done ¶ added in v0.5.0
func (c *WebSocketConn) Done() <-chan struct{}
Done is closed when the connection closes; the transport selects on it to stop writing. It is part of the engine-facing seam, not the application API. Inputs: - none Outputs: - <-chan struct{}: channel closed once Close has run.
func (*WebSocketConn) Outbound ¶ added in v0.5.0
func (c *WebSocketConn) Outbound() <-chan WebSocketFrame
Outbound is the transport's receive end for queued frames; the writer goroutine ranges over it. It is part of the engine-facing seam, not the application API. Inputs: - none Outputs: - <-chan WebSocketFrame: frames enqueued by Send*, in send order.
func (*WebSocketConn) Request ¶ added in v0.5.0
func (c *WebSocketConn) Request() *Request
Request returns the upgrade-time request, including Internal values set by security layers. Inputs: - none Outputs: - *Request: request translated from the WebSocket handshake.
func (*WebSocketConn) Send ¶ added in v0.5.0
func (c *WebSocketConn) Send(message []byte) error
Send enqueues a binary frame for delivery to the client. Inputs: - message: payload written to the client as one binary frame. Outputs: - error: ErrWebSocketClosed when the connection is closed or was closed as a slow consumer.
func (*WebSocketConn) SendJSON ¶ added in v0.5.0
func (c *WebSocketConn) SendJSON(v any) error
SendJSON marshals a value and enqueues it as one JSON text frame. Inputs: - v: value marshalled with encoding/json. Outputs: - error: the marshal error when encoding fails, otherwise ErrWebSocketClosed when the connection is closed.
func (*WebSocketConn) SendText ¶ added in v0.5.0
func (c *WebSocketConn) SendText(message string) error
SendText enqueues a text frame for delivery to the client. Inputs: - message: payload written to the client as one text frame. Outputs: - error: ErrWebSocketClosed when the connection is closed or was closed as a slow consumer.
type WebSocketFrame ¶ added in v0.5.0
type WebSocketFrame struct {
Binary bool // false sends a text frame, true sends a binary frame
Data []byte
}
WebSocketFrame is one queued outbound frame. The transport's writer goroutine receives these from a connection's Outbound channel; application code never constructs one and uses WebSocketConn.Send* instead.
type WebSocketHub ¶ added in v0.5.0
type WebSocketHub struct {
// contains filtered or unexported fields
}
WebSocketHub fans messages out to the connections of one WebSocket route.
Every route registered with Server.WebSocket owns exactly one hub, returned at registration time and retrievable later via Server.WebSocketHub. Broadcast* methods reach every connection; Publish* methods reach only connections subscribed to a topic — an arbitrary string such as "user:42" or "room:lobby". Register and Unregister are the engine-facing seam that ties connection lifecycle to the hub; application code does not call them.
func (*WebSocketHub) Broadcast ¶ added in v0.5.0
func (h *WebSocketHub) Broadcast(message []byte)
Broadcast sends a binary message to every connection in the hub. Inputs: - message: payload delivered to each connection as a binary frame. Outputs: - none
func (*WebSocketHub) BroadcastJSON ¶ added in v0.5.0
func (h *WebSocketHub) BroadcastJSON(v any) error
BroadcastJSON marshals a value once and sends it to every connection as a JSON text frame. Inputs: - v: value marshalled with encoding/json. Outputs: - error: non-nil when marshalling fails; nothing is sent in that case.
func (*WebSocketHub) BroadcastText ¶ added in v0.5.0
func (h *WebSocketHub) BroadcastText(message string)
BroadcastText sends a text message to every connection in the hub. Inputs: - message: payload delivered to each connection as a text frame. Outputs: - none
func (*WebSocketHub) ConnectionCount ¶ added in v0.5.0
func (h *WebSocketHub) ConnectionCount() int
ConnectionCount reports how many connections are currently registered in the hub. Inputs: - none Outputs: - int: number of connected clients.
func (*WebSocketHub) Publish ¶ added in v0.5.0
func (h *WebSocketHub) Publish(topic string, message []byte)
Publish sends a binary message to every connection subscribed to a topic. Inputs: - topic: topic string whose subscribers receive the message. - message: payload delivered to each subscriber as a binary frame. Outputs: - none
func (*WebSocketHub) PublishJSON ¶ added in v0.5.0
func (h *WebSocketHub) PublishJSON(topic string, v any) error
PublishJSON marshals a value once and sends it to a topic's subscribers as a JSON text frame. Inputs: - topic: topic string whose subscribers receive the message. - v: value marshalled with encoding/json. Outputs: - error: non-nil when marshalling fails; nothing is sent in that case.
func (*WebSocketHub) PublishText ¶ added in v0.5.0
func (h *WebSocketHub) PublishText(topic string, message string)
PublishText sends a text message to every connection subscribed to a topic. Inputs: - topic: topic string whose subscribers receive the message. - message: payload delivered to each subscriber as a text frame. Outputs: - none
func (*WebSocketHub) Register ¶ added in v0.5.0
func (h *WebSocketHub) Register(conn *WebSocketConn)
Register adds a connection to the hub; engines call it after a successful upgrade. Inputs: - conn: newly connected client to include in broadcasts. Outputs: - none
func (*WebSocketHub) Subscribe ¶ added in v0.5.0
func (h *WebSocketHub) Subscribe(conn *WebSocketConn, topic string)
Subscribe adds a registered connection to a topic so Publish* calls for that topic reach it. Inputs: - conn: connection to subscribe; ignored when it is not registered in the hub. - topic: arbitrary topic string, for example "user:42". Outputs: - none
func (*WebSocketHub) Unregister ¶ added in v0.5.0
func (h *WebSocketHub) Unregister(conn *WebSocketConn)
Unregister removes a connection and all its topic subscriptions; engines call it on disconnect. Inputs: - conn: departing client to exclude from further broadcasts and publishes. Outputs: - none
func (*WebSocketHub) Unsubscribe ¶ added in v0.5.0
func (h *WebSocketHub) Unsubscribe(conn *WebSocketConn, topic string)
Unsubscribe removes a connection from a topic. Inputs: - conn: connection to remove from the topic's subscriber set. - topic: topic string the connection no longer wants. Outputs: - none
type WebSocketRoute ¶ added in v0.5.0
type WebSocketRoute struct {
Path string
SecurityLayer []string
MaxMessageSize int64
CheckOrigin func(req *Request) bool
OnConnect func(conn *WebSocketConn)
OnMessage func(conn *WebSocketConn, message []byte)
OnDisconnect func(conn *WebSocketConn)
}
WebSocketRoute configures a single WebSocket route.
Path is required and is matched exactly, like PageRoute.Path. The route accepts only GET requests carrying a WebSocket upgrade handshake; security layers run BEFORE the connection is upgraded, so a rejected client receives a plain HTTP 401 and never opens a socket.
All lifecycle callbacks are optional. OnConnect runs after the connection has been registered in the route's hub, OnMessage runs once per client frame (text or binary), and OnDisconnect runs after the connection has been unregistered — a message published from OnDisconnect never reaches the departing client.
CheckOrigin is optional: when nil, engines apply a same-host origin policy (browser cross-origin connections are refused). MaxMessageSize is optional: when 0, engines apply their default inbound frame limit.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
bungo
command
|
|
|
aws
module
|
|
|
gcp
module
|
|
|
internal
|
|
|
wsbridge
Package wsbridge is the internal seam BunGo's engine packages use to resolve a registered WebSocket route's hub, without the core package exposing that lookup on its public API.
|
Package wsbridge is the internal seam BunGo's engine packages use to resolve a registered WebSocket route's hub, without the core package exposing that lookup on its public API. |
