web

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 18, 2026 License: MIT Imports: 25 Imported by: 0

README

🌐 web — Flask-inspired web server for Starlark

Go Reference license Go Report Card codecov binary footprint

Build server-side HTTP applications from Starlark with a Flask-inspired API: routing, route groups, path-pattern middleware, request/response helpers, pluggable authentication, and custom error handlers — on top of gin.

Overview

Within the Star* ecosystem starpkg is "support for necessary local operations plus simple abstractions over common online services, for ease of use." web is a local capability: it stands up an HTTP listener inside the host process so a script can serve requests (the inverse of an HTTP client — for outbound calls use starlet's http module).

  • Routingcreate_server returns a server with per-method registrars (get/post/put/…), route, and route groups; Flask-style /{id} path parameters.
  • Responses — builders for plain, JSON, HTML, text, file, download, and redirect/error responses, returned from a func(req) handler.
  • Middleware — built-in CORS, logging, security headers, timing, JSON, compression, rate limiting, caching, and request-size limits, plus custom func(req, next) middleware, attached globally or per path pattern.
  • Authentication — pluggable api_key_auth, bearer_auth, and basic_auth authenticators that yield middleware.
  • Safe by default — a default-deny loopback bind guardrail keeps a server started from an untrusted script off the network unless the host opts in with allow_public_bind.

For the complete per-builtin / per-object-method reference — signatures, parameters, returns, errors, examples — and the configuration accessors, see docs/API.md.

Installation

go get github.com/starpkg/web

Quick start

Wire the module into a Starlet interpreter, then load("web", …) from a script:

package main

import (
    "github.com/1set/starlet"
    "github.com/starpkg/web"
)

func main() {
    machine := starlet.NewWithNames(nil, []string{"go_idiomatic"}, nil)
    machine.AddLazyloadModules(starlet.ModuleLoaderMap{
        web.ModuleName: web.NewModule().LoadModule(),
    })
    _, err := machine.RunScript([]byte(`
load("web", "create_server", "html_response", "json_response")

srv = create_server(host="localhost", port=8080)
srv.get("/", lambda req: html_response("<h1>Hello, World!</h1>"))
srv.get("/users/{id}", lambda req: json_response({"id": req.param("id")}))
srv.run()
`), nil)
    if err != nil {
        panic(err)
    }
}

A script loads the module, calls create_server to get a server object, registers route handlers (each a func(req) returning a response), and starts it with srv.start() (non-blocking) or srv.run() (blocking).

Starlark API at a glance

Module builtins (load("web", …)):

  • create_server(host?, port?, server_header?) — create an HTTP server object.
  • response(body, status?, headers?) — plain response.
  • json_response(data, status?, headers?) — JSON response.
  • html_response(content, status?, headers?) — HTML response.
  • text_response(text, status?) — plain-text response.
  • file_response(filepath, content_type?, filename?) — serve a file (optionally as a download).
  • send_file(filepath, content_type?) — serve a file.
  • send_data(data, filename, content_type?) — send in-memory data as a download.
  • static_dir(root, index?, spa?, cache_control?) — read-only static-file root for srv.static (safe by default: no traversal/dotfiles/listing).
  • redirect(location, status?) — redirect response.
  • error_response(status, message?) — error response.
  • api_key_auth(keys?, header?, query_param?) — API-key authenticator.
  • bearer_auth(validate_func, header?) — bearer-token authenticator.
  • basic_auth(users?, realm?) — HTTP Basic authenticator.
  • cors_middleware(origins?, methods?, headers?, credentials?) — CORS middleware.
  • logging_middleware(format?) — request logging middleware.
  • security_headers_middleware(frame_options?, content_type_options?, xss_protection?, hsts?, csp?, referrer_policy?) — security headers middleware.
  • timing_middleware(header?) — response-time header middleware.
  • json_middleware() — JSON request/response middleware.
  • compression_middleware(level?, min_size?, types?) — gzip compression middleware.
  • rate_limit_middleware(requests?, window?, key_func?) — per-key rate limiting middleware.
  • cache_middleware(max_age?, private?, patterns?, vary?)Cache-Control middleware.
  • request_size_middleware(max_content_length?, max_url_length?, max_headers?) — request-size limiting middleware.

Server object: get / post / put / delete / patch / options / head, route, group, static (mount a static_dir), use, use_for, error_handler, start, stop, run, is_running.

Request object — properties method, url, path, host, remote, client_ip, proto, headers, query, context; methods body, json, form, files, cookie, param, get_header, bearer_token, basic_auth. Uploaded-file entries expose read.

Response object — settable status_code, headers, body, file_path; methods set_header, get_header, set_cookie, delete_cookie. Authenticators expose middleware. Custom middleware receives a next callable.

See docs/API.md for the full signatures, return values, errors, and examples of every builtin and method above.

Configuration

The module's options (host, port, read_timeout, write_timeout, max_body_size, debug_mode, server_header, allow_public_bind) are configured via environment variables (WEB_*) or per-option get_<key> / set_<key> accessor builtins, and serve as defaults for the servers the module creates. The opt-in allow_public_bind lever lets the host expose a server beyond loopback; it defaults to off. See the Configuration section of docs/API.md for the full option table, defaults, accessors, and the bind-guardrail details.

License

This project is licensed under the MIT License — see the LICENSE file for details.

Documentation

Overview

Package web provides a Starlark module for server-side web applications. It offers a Flask-inspired API for building HTTP servers with routing, route groups, path-pattern middleware, request/response handling, pluggable authentication, and custom error handlers, built on top of gin.

Example (BasicWebServer)
script := `
load("web", "create_server", "response", "json_response")

def main():
    # Create server
    srv = create_server(host="localhost", port=8080)
    
    # Simple text response
    def home(req):
        return response("Welcome to Starlark Web!")
    
    # JSON API endpoint
    def api_info(req):
        return json_response({
            "name": "Starlark Web API",
            "version": "1.0",
            "method": req.method,
            "path": req.path,
        })
    
    # Register routes
    srv.get("/", home)
    srv.get("/api/info", api_info)
    
    print("Server created successfully")
    
    # Start server
    srv.start()
    
    # TODO: make something calling via http package to verify the response
    
    # Stop server
    srv.stop()

main()
`

// Create machine with web module
machine := starlet.NewWithNames(starlet.StringAnyMap{}, []string{"go_idiomatic", "http"}, []string{})
machine.SetPrintFunc(func(thread *starlark.Thread, msg string) {
	// Print function for testing
	fmt.Println(msg)
})

// Load web module
webModule := NewModule()
machine.AddLazyloadModules(starlet.ModuleLoaderMap{
	ModuleName: webModule.LoadModule(),
})

_, err := machine.RunScript([]byte(script), nil)
if err != nil {
	panic(err)
}
Output:
Server created successfully

Index

Examples

Constants

View Source
const (
	MIMEApplicationJSON        = "application/json"
	MIMEApplicationJavaScript  = "application/javascript"
	MIMETextHTML               = "text/html"
	MIMETextPlain              = "text/plain"
	MIMETextCSS                = "text/css"
	MIMETextJavaScript         = "text/javascript"
	MIMEMultipartForm          = "multipart/form-data"
	MIMEApplicationForm        = "application/x-www-form-urlencoded"
	MIMEApplicationOctetStream = "application/octet-stream"
)

MIME types

View Source
const (
	HeaderContentType        = "Content-Type"
	HeaderContentLength      = "Content-Length"
	HeaderContentDisposition = "Content-Disposition"
	HeaderContentEncoding    = "Content-Encoding"
	HeaderAuthorization      = "Authorization"
	HeaderWWWAuthenticate    = "WWW-Authenticate"
	HeaderAPIKey             = "X-API-Key"
	HeaderCacheControl       = "Cache-Control"
	HeaderServer             = "Server"
	HeaderLocation           = "Location"
	HeaderVary               = "Vary"
	HeaderRetryAfter         = "Retry-After"

	// CORS headers
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"

	// Response time header
	HeaderXResponseTime = "X-Response-Time"

	// Rate limiting headers
	HeaderXRateLimitLimit     = "X-RateLimit-Limit"
	HeaderXRateLimitRemaining = "X-RateLimit-Remaining"
	HeaderXRateLimitReset     = "X-RateLimit-Reset"
)

Header names

View Source
const ModuleName = "web"

ModuleName defines the expected name for this module when used in Starlark's load() function

Variables

View Source
var DefaultPathMatcher = NewPathMatcher()

DefaultPathMatcher is a singleton instance for global use.

Functions

func ExtractParams

func ExtractParams(requestPath, pattern string) map[string]string

ExtractParams is a convenience function that uses the default PathMatcher.

func IsValidPattern

func IsValidPattern(pattern string) bool

IsValidPattern is a convenience function that uses the default PathMatcher.

func MatchesAny

func MatchesAny(requestPath string, patterns []string) bool

MatchesAny is a convenience function that uses the default PathMatcher.

func MatchesPattern

func MatchesPattern(requestPath, pattern string) bool

MatchesPattern is a convenience function that uses the default PathMatcher.

func NormalizePath

func NormalizePath(inputPath string) string

NormalizePath is a convenience function that uses the default PathMatcher.

Types

type AuthResult

type AuthResult struct {
	Success   bool
	UserInfo  interface{}
	ErrorCode int
	Message   string
}

AuthResult represents the result of authentication

type Authenticator

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

Authenticator represents an authentication handler that can be used as middleware

func (*Authenticator) Middleware

func (a *Authenticator) Middleware() MiddlewareFunc

Middleware returns a middleware function for this authenticator

type AuthenticatorWrapper

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

AuthenticatorWrapper wraps the Authenticator for Starlark

func NewAuthenticatorWrapper

func NewAuthenticatorWrapper(auth *Authenticator) *AuthenticatorWrapper

NewAuthenticatorWrapper creates a new wrapper

func (*AuthenticatorWrapper) Attr

func (aw *AuthenticatorWrapper) Attr(name string) (starlark.Value, error)

Attr returns the named attribute

func (*AuthenticatorWrapper) AttrNames

func (aw *AuthenticatorWrapper) AttrNames() []string

AttrNames returns available attributes

func (*AuthenticatorWrapper) Freeze

func (aw *AuthenticatorWrapper) Freeze()

Freeze makes the object immutable

func (*AuthenticatorWrapper) Hash

func (aw *AuthenticatorWrapper) Hash() (uint32, error)

Hash returns a hash value

func (*AuthenticatorWrapper) String

func (aw *AuthenticatorWrapper) String() string

String returns string representation

func (*AuthenticatorWrapper) Truth

func (aw *AuthenticatorWrapper) Truth() starlark.Bool

Truth returns the truth value

func (*AuthenticatorWrapper) Type

func (aw *AuthenticatorWrapper) Type() string

Type returns the Starlark type name

type ErrorHandler

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

ErrorHandler represents a custom error handler function

type ErrorHandlerRegistry

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

ErrorHandlerRegistry manages custom error handlers

func NewErrorHandlerRegistry

func NewErrorHandlerRegistry() *ErrorHandlerRegistry

NewErrorHandlerRegistry creates a new error handler registry

func (*ErrorHandlerRegistry) GetHandler

func (ehr *ErrorHandlerRegistry) GetHandler(statusCode int) starlark.Callable

GetHandler returns the handler for a specific status code

func (*ErrorHandlerRegistry) HandleError

func (ehr *ErrorHandlerRegistry) HandleError(statusCode int, req *Request) *Response

HandleError calls the appropriate error handler or returns a default error response

func (*ErrorHandlerRegistry) RegisterHandler

func (ehr *ErrorHandlerRegistry) RegisterHandler(statusCodes []int, handler starlark.Callable)

RegisterHandler registers an error handler for specific status codes

type ErrorResponse

type ErrorResponse struct {
	Error   string `json:"error"`
	Message string `json:"message,omitempty"`
	Code    int    `json:"code"`
}

ErrorResponse represents a standardized error response. This structure provides a consistent format for all HTTP error responses throughout the web module, including error message, HTTP status code, and description.

type HTTPMethod

type HTTPMethod string

HTTPMethod represents the supported HTTP methods

const (
	MethodGet     HTTPMethod = http.MethodGet
	MethodPost    HTTPMethod = http.MethodPost
	MethodPut     HTTPMethod = http.MethodPut
	MethodDelete  HTTPMethod = http.MethodDelete
	MethodPatch   HTTPMethod = http.MethodPatch
	MethodOptions HTTPMethod = http.MethodOptions
	MethodHead    HTTPMethod = http.MethodHead
)

Supported HTTP methods, used by route registration.

type MemoryRateLimitStorage

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

MemoryRateLimitStorage implements in-memory rate limiting storage

func NewMemoryRateLimitStorage

func NewMemoryRateLimitStorage() *MemoryRateLimitStorage

NewMemoryRateLimitStorage creates a new memory-based rate limit storage

func (*MemoryRateLimitStorage) Get

func (m *MemoryRateLimitStorage) Get(key string) (int, error)

func (*MemoryRateLimitStorage) Increment

func (m *MemoryRateLimitStorage) Increment(key string, ttl time.Duration) (int, error)

func (*MemoryRateLimitStorage) Set

func (m *MemoryRateLimitStorage) Set(key string, value int, ttl time.Duration) error

type Middleware

type Middleware struct {
	Pattern string
	Handler MiddlewareFunc
}

Middleware represents middleware with a specific path pattern. All middleware in the system has an associated path pattern. Global middleware uses the pattern "/*" to match all paths.

func (*Middleware) MatchesPath

func (m *Middleware) MatchesPath(path string) bool

MatchesPath checks if the given path matches the middleware pattern. Uses the unified PathMatcher for consistent path matching behavior.

type MiddlewareFunc

type MiddlewareFunc func(*Request, NextFunc) *Response

MiddlewareFunc represents a middleware function

type MiddlewareWrapper

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

MiddlewareWrapper wraps a middleware function for Starlark

func NewMiddlewareWrapper

func NewMiddlewareWrapper(middleware MiddlewareFunc) *MiddlewareWrapper

NewMiddlewareWrapper creates a new middleware wrapper

func (*MiddlewareWrapper) Attr

func (mw *MiddlewareWrapper) Attr(name string) (starlark.Value, error)

Attr returns the named attribute (none for now)

func (*MiddlewareWrapper) AttrNames

func (mw *MiddlewareWrapper) AttrNames() []string

AttrNames returns available attributes

func (*MiddlewareWrapper) Execute

func (mw *MiddlewareWrapper) Execute(req *Request, next NextFunc) *Response

Execute runs the middleware function

func (*MiddlewareWrapper) Freeze

func (mw *MiddlewareWrapper) Freeze()

Freeze makes the object immutable

func (*MiddlewareWrapper) Hash

func (mw *MiddlewareWrapper) Hash() (uint32, error)

Hash returns a hash value

func (*MiddlewareWrapper) String

func (mw *MiddlewareWrapper) String() string

String returns string representation

func (*MiddlewareWrapper) Truth

func (mw *MiddlewareWrapper) Truth() starlark.Bool

Truth returns the truth value

func (*MiddlewareWrapper) Type

func (mw *MiddlewareWrapper) Type() string

Type returns the Starlark type name

type Module

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

Module wraps the ConfigurableModule with specific functionality for web server

func NewModule

func NewModule() *Module

NewModule creates a new instance of Module with default configurations. This is the primary entry point for creating a web module that can be loaded into a Starlark environment. The module provides functions for creating HTTP servers, handling requests and responses, and managing web application lifecycle.

func (*Module) LoadModule

func (m *Module) LoadModule() starlet.ModuleLoader

LoadModule returns the Starlark module loader with web-specific functions. This method provides the complete set of web module functions that can be called from Starlark scripts, including server creation and response builders.

type NextFunc

type NextFunc func(*Request) *Response

NextFunc represents the next handler in the middleware chain

type PathMatcher

type PathMatcher struct{}

PathMatcher provides unified path matching functionality using sophisticated algorithms. This utility consolidates all path matching logic in the web package and provides consistent path matching behavior across the module.

func NewPathMatcher

func NewPathMatcher() *PathMatcher

NewPathMatcher creates a new PathMatcher instance.

func (*PathMatcher) ExtractParams

func (pm *PathMatcher) ExtractParams(requestPath, pattern string) map[string]string

ExtractParams extracts path parameters from a request path using a parameter pattern. Returns a map of parameter names to values, or nil if the pattern doesn't match.

func (*PathMatcher) IsValidPattern

func (pm *PathMatcher) IsValidPattern(pattern string) bool

IsValidPattern checks if a pattern is valid for path matching. This validates the pattern syntax and ensures it's properly formatted.

func (*PathMatcher) MatchesAny

func (pm *PathMatcher) MatchesAny(requestPath string, patterns []string) bool

MatchesAny checks if a path matches any of the given patterns. This is useful for middleware that needs to apply to multiple patterns.

func (*PathMatcher) MatchesPattern

func (pm *PathMatcher) MatchesPattern(requestPath, pattern string) bool

MatchesPattern checks if a path matches a glob-like pattern. This method supports various pattern types: - Exact matches: "/api/users" matches "/api/users" exactly - Glob patterns: "/api/*" matches "/api/users", "/api/posts", etc. - Prefix patterns: "/api/admin/*" matches "/api/admin/users", "/api/admin/posts", etc. - Parameter patterns: "/users/{id}" matches "/users/123", "/users/abc", etc.

The method leverages Gin's internal path matching algorithm for consistency with the main router's behavior.

func (*PathMatcher) NormalizePath

func (pm *PathMatcher) NormalizePath(inputPath string) string

NormalizePath normalizes a path by cleaning it and ensuring it has proper format. This uses Go's standard path.Clean function for consistency.

type RateLimitStorage

type RateLimitStorage interface {
	Get(key string) (int, error)
	Set(key string, value int, ttl time.Duration) error
	Increment(key string, ttl time.Duration) (int, error)
}

RateLimitStorage interface for rate limiting storage backends

type Request

type Request struct {
	Method   string                 `json:"method"`
	URL      string                 `json:"url"`
	Path     string                 `json:"path"`
	Host     string                 `json:"host"`
	Remote   string                 `json:"remote"`
	ClientIP string                 `json:"client_ip"`
	Proto    string                 `json:"proto"`
	Headers  map[string]string      `json:"headers"`
	Query    map[string]string      `json:"query"`
	Context  map[string]interface{} `json:"context"`
	// contains filtered or unexported fields
}

Request represents an HTTP request. This structure holds the complete request data including method, URL, headers, query parameters, and provides access to the underlying gin context for advanced request processing.

type RequestWrapper

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

RequestWrapper wraps the Request struct to provide Starlark-compatible interface. This wrapper exposes request properties and methods to Starlark scripts, allowing access to request data, headers, parameters, and body content.

func NewRequestWrapper

func NewRequestWrapper(request *Request) *RequestWrapper

NewRequestWrapper creates a new RequestWrapper. This function wraps a Request to make it accessible from Starlark with proper attribute access and method calls.

func (*RequestWrapper) Attr

func (rw *RequestWrapper) Attr(name string) (starlark.Value, error)

Attr returns the value of a request attribute. This method provides access to request properties and methods from Starlark.

func (*RequestWrapper) AttrNames

func (rw *RequestWrapper) AttrNames() []string

AttrNames returns the list of available attributes.

func (*RequestWrapper) Freeze

func (rw *RequestWrapper) Freeze()

Freeze makes the request immutable (required by Starlark).

func (*RequestWrapper) Hash

func (rw *RequestWrapper) Hash() (uint32, error)

Hash returns a hash of the request (not supported).

func (*RequestWrapper) String

func (rw *RequestWrapper) String() string

String returns a string representation of the request.

func (*RequestWrapper) Truth

func (rw *RequestWrapper) Truth() starlark.Bool

Truth returns the truth value of the request (always true).

func (*RequestWrapper) Type

func (rw *RequestWrapper) Type() string

Type returns the Starlark type name.

type Response

type Response struct {
	StatusCode int               `json:"status_code"`
	Headers    map[string]string `json:"headers"`
	Body       string            `json:"body"`
	FilePath   string            `json:"file_path,omitempty"`
	// Cookies holds Set-Cookie header values separately from Headers, because
	// Set-Cookie is not comma-combinable: each cookie must be emitted as its
	// own header line. applyResponse writes one Add("Set-Cookie", v) per entry.
	Cookies []string `json:"cookies,omitempty"`
}

Response represents an HTTP response. This structure holds the complete response data including status code, headers, body content, and optional file path for file responses.

type ResponseWrapper

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

ResponseWrapper wraps the Response struct to provide Starlark-compatible interface. This wrapper exposes response properties and methods to Starlark scripts, allowing manipulation of cookies and access to response metadata.

func NewResponseWrapper

func NewResponseWrapper(response *Response) *ResponseWrapper

NewResponseWrapper creates a new ResponseWrapper. This function wraps a Response to make it accessible from Starlark with proper attribute access and method calls.

func (*ResponseWrapper) Attr

func (rw *ResponseWrapper) Attr(name string) (starlark.Value, error)

Attr returns the value of the specified attribute

func (*ResponseWrapper) AttrNames

func (rw *ResponseWrapper) AttrNames() []string

AttrNames returns the list of available attributes

func (*ResponseWrapper) Freeze

func (rw *ResponseWrapper) Freeze()

Freeze marks the response as frozen (immutable)

func (*ResponseWrapper) Hash

func (rw *ResponseWrapper) Hash() (uint32, error)

Hash returns the hash of the response (not supported)

func (*ResponseWrapper) SetField

func (rw *ResponseWrapper) SetField(name string, value starlark.Value) error

SetField sets the value of the specified field

func (*ResponseWrapper) String

func (rw *ResponseWrapper) String() string

String returns the string representation of the response

func (*ResponseWrapper) Truth

func (rw *ResponseWrapper) Truth() starlark.Bool

Truth returns the truth value of the response

func (*ResponseWrapper) Type

func (rw *ResponseWrapper) Type() string

Type returns the type name for Starlark

type RouteGroup

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

RouteGroup represents a group of routes with a common prefix. This structure provides a way to organize related routes together and apply common middleware or configuration to them.

func (*RouteGroup) Delete

func (rg *RouteGroup) Delete(path string, handler starlark.Callable) error

func (*RouteGroup) Get

func (rg *RouteGroup) Get(path string, handler starlark.Callable) error

HTTP method handlers for RouteGroup

func (*RouteGroup) Head

func (rg *RouteGroup) Head(path string, handler starlark.Callable) error

func (*RouteGroup) Options

func (rg *RouteGroup) Options(path string, handler starlark.Callable) error

func (*RouteGroup) Patch

func (rg *RouteGroup) Patch(path string, handler starlark.Callable) error

func (*RouteGroup) Post

func (rg *RouteGroup) Post(path string, handler starlark.Callable) error

func (*RouteGroup) Put

func (rg *RouteGroup) Put(path string, handler starlark.Callable) error

func (*RouteGroup) RegisterRoute

func (rg *RouteGroup) RegisterRoute(method HTTPMethod, path string, handler gin.HandlerFunc) error

RegisterRoute implements RouteRegistrar for RouteGroup

type RouteGroupWrapper

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

RouteGroupWrapper wraps the RouteGroup struct to provide Starlark-compatible method names. This wrapper exposes route group methods to Starlark scripts with lowercase names that match the expected API conventions.

func NewRouteGroupWrapper

func NewRouteGroupWrapper(group *RouteGroup) *RouteGroupWrapper

NewRouteGroupWrapper creates a new RouteGroupWrapper with initialized method map

func (*RouteGroupWrapper) Attr

func (rgw *RouteGroupWrapper) Attr(name string) (starlark.Value, error)

Attr returns the value of the named attribute using efficient map lookup.

func (*RouteGroupWrapper) AttrNames

func (rgw *RouteGroupWrapper) AttrNames() []string

AttrNames returns the names of all attributes.

func (*RouteGroupWrapper) Freeze

func (rgw *RouteGroupWrapper) Freeze()

Freeze makes this object immutable.

func (*RouteGroupWrapper) Hash

func (rgw *RouteGroupWrapper) Hash() (uint32, error)

Hash returns a hash value for this object.

func (*RouteGroupWrapper) String

func (rgw *RouteGroupWrapper) String() string

String returns a string representation of the RouteGroupWrapper.

func (*RouteGroupWrapper) Truth

func (rgw *RouteGroupWrapper) Truth() starlark.Bool

Truth returns the truth value of this object.

func (*RouteGroupWrapper) Type

func (rgw *RouteGroupWrapper) Type() string

Type returns the Starlark type name for this object.

type RouteRegistrar

type RouteRegistrar interface {
	RegisterRoute(method HTTPMethod, path string, handler gin.HandlerFunc) error
}

RouteRegistrar defines the interface for registering routes

type Server

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

Server represents an HTTP server instance

func (*Server) Delete

func (s *Server) Delete(path string, handler starlark.Callable) error

func (*Server) Get

func (s *Server) Get(path string, handler starlark.Callable) error

HTTP method handlers for Server

func (*Server) Group

func (s *Server) Group(prefix string) *RouteGroup

Group creates a route group. This method creates a new route group with the specified prefix, allowing for organized route registration and middleware application to related endpoints.

func (*Server) Head

func (s *Server) Head(path string, handler starlark.Callable) error

func (*Server) IsRunning

func (s *Server) IsRunning() bool

IsRunning returns whether the server is running

func (*Server) Options

func (s *Server) Options(path string, handler starlark.Callable) error

func (*Server) Patch

func (s *Server) Patch(path string, handler starlark.Callable) error

func (*Server) Post

func (s *Server) Post(path string, handler starlark.Callable) error

func (*Server) Put

func (s *Server) Put(path string, handler starlark.Callable) error

func (*Server) RegisterRoute

func (s *Server) RegisterRoute(method HTTPMethod, path string, handler gin.HandlerFunc) error

RegisterRoute implements RouteRegistrar for Server

func (*Server) RegisterStatic

func (s *Server) RegisterStatic(prefix string, sd *StaticDir) error

RegisterStatic mounts a StaticDir at prefix. Most-specific (longest) prefix wins when several mounts overlap.

func (*Server) Route

func (s *Server) Route(methods interface{}, path string, handler starlark.Callable) error

Route adds a route with specific method(s). This method accepts either a single method string or a list of method strings, allowing the same handler to respond to multiple HTTP methods on the same path.

func (*Server) Run

func (s *Server) Run() error

Run starts the server and blocks. This method starts the HTTP server and blocks the current thread until the server is stopped or encounters an error, suitable for simple applications.

func (*Server) Start

func (s *Server) Start() error

Start starts the server in a goroutine. This method begins listening for HTTP requests on the configured host and port without blocking the current thread, allowing for asynchronous server operation.

func (*Server) Stop

func (s *Server) Stop() error

Stop stops the server

type ServerWrapper

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

ServerWrapper wraps the Server struct to provide Starlark-compatible method names

func NewServerWrapper

func NewServerWrapper(server *Server) *ServerWrapper

NewServerWrapper creates a new ServerWrapper with initialized method maps

func (*ServerWrapper) Attr

func (sw *ServerWrapper) Attr(name string) (starlark.Value, error)

func (*ServerWrapper) AttrNames

func (sw *ServerWrapper) AttrNames() []string

func (*ServerWrapper) Freeze

func (sw *ServerWrapper) Freeze()

func (*ServerWrapper) Hash

func (sw *ServerWrapper) Hash() (uint32, error)

func (*ServerWrapper) String

func (sw *ServerWrapper) String() string

func (*ServerWrapper) Truth

func (sw *ServerWrapper) Truth() starlark.Bool

func (*ServerWrapper) Type

func (sw *ServerWrapper) Type() string

type StaticDir

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

StaticDir is a read-only static-file root mounted on a server with srv.static(prefix, dir). It is created by static_dir(). It is a configuration handle, not a response — it carries no script-callable methods.

func (*StaticDir) Freeze

func (sd *StaticDir) Freeze()

func (*StaticDir) Hash

func (sd *StaticDir) Hash() (uint32, error)

func (*StaticDir) String

func (sd *StaticDir) String() string

func (*StaticDir) Truth

func (sd *StaticDir) Truth() starlark.Bool

func (*StaticDir) Type

func (sd *StaticDir) Type() string

Jump to

Keyboard shortcuts

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