Documentation
¶
Overview ¶
Package proteus provides a versatile web server framework for Go, inspired by Node.js Express. It offers a simple and intuitive API for building HTTP servers with support for routing, middleware, request/response handling, and various HTTP status codes and logging formats.
Index ¶
Constants ¶
const ( // INFO_LEVEL represents informational messages that highlight normal server operation. // Use this level for general operational messages that might be useful for debugging. INFO_LEVEL = internal.INFO_LEVEL // ERROR_LEVEL represents error conditions that require immediate attention. // Use this level for exceptions, failures, and other critical issues. ERROR_LEVEL = internal.ERROR_LEVEL // WARN_LEVEL represents potentially harmful situations that don't stop the server. // Use this level for deprecated API usage, recoverable errors, or unusual conditions. WARN_LEVEL = internal.WARN_LEVEL )
Logging levels available for server logs. These constants define the severity levels for log messages output by the server.
const ( // COMMON_LOGGER uses the Common Log Format (CLF) as defined in Apache HTTP Server. // Format: :remote-addr [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] // Example: 127.0.0.1 [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326 COMMON_LOGGER = internal.COMMON_LOGGER // DEV_LOGGER provides a concise format suitable for development environments. // Format: :method :url :status :response-time ms - :res[content-length] // Example: GET / 200 15.456 ms - 1234 DEV_LOGGER = internal.DEV_LOGGER // TINY_LOGGER provides the most minimal logging format. // Format: :method :url :status :res[content-length] - :response-time ms // Example: GET / 200 1234 - 15.456 ms TINY_LOGGER = internal.TINY_LOGGER // SHORT_LOGGER provides a balance between information and brevity. // Format: :remote-addr :method :url HTTP/:http-version :status :res[content-length] - :response-time ms // Example: 127.0.0.1 GET / HTTP/1.1 200 1234 - 15.456 ms SHORT_LOGGER = internal.SHORT_LOGGER )
Logging formats for HTTP request processing logs. These constants define different predefined formats for logging HTTP requests and responses, similar to Apache and other web server logging formats.
Variables ¶
var CreateRouter = internal.NewRouter
CreateRouter creates a new router instance for organizing and grouping HTTP route definitions. Routers provide a way to create modular, mountable route handlers that can be combined and reused across different parts of an application.
Returns a pointer to a Router instance that can define routes and middleware independently from the main server instance. The router must be mounted on a server or another router using the Use() method to become functional.
Example usage:
router := proteus.CreateRouter()
// Define routes on the router
router.Get("/users", getUsersHandler)
router.Post("/users", createUserHandler)
router.Get("/users/:id", getUserByIdHandler)
// Apply middleware to all routes in this router
router.Use(authenticationMiddleware)
// Mount the router on a server or another router
server.Use("/api", router)
Router instances support:
- All HTTP method handlers: Get(), Post(), Put(), Delete(), etc.
- Middleware registration: Use()
- Route parameters: /users/:id, /posts/:slug
- Nested routing: mounting routers within other routers
var CreateServer = internal.NewServer
CreateServer creates a new HTTP server instance capable of accepting and processing HTTP requests. The server supports HTTP/0.9, HTTP/1.0, and HTTP/1.1 protocols and provides Express.js-like functionality including routing, middleware support, and request/response handling.
Returns a pointer to an HttpServer instance that can be configured with routes and middleware before being started with the Listen() method.
Example usage:
server := proteus.CreateServer()
// Configure routes
server.Get("/", func(req *proteus.HttpRequest, res *proteus.HttpResponse) {
res.Send("Hello, World!")
})
// Start listening on port 8080
server.Listen(8080, "localhost")
The server instance provides methods for:
- HTTP method handlers: Get(), Post(), Put(), Delete(), Patch(), etc.
- Middleware registration: Use()
- Static file serving: Static()
- Server lifecycle: Listen(), Close()
var JsonParser = internal.JsonParser
JsonParser is middleware that automatically parses incoming JSON request payloads and makes the parsed data available in the request's Body field. This middleware should be applied to routes that expect to receive JSON data in the request body (typically POST, PUT, PATCH requests).
The middleware:
- Checks for Content-Type: application/json header
- Parses the JSON payload from the request body
- Stores the parsed data in req.Body as a map[string]interface{}
- Handles parsing errors gracefully by returning appropriate HTTP error responses
Usage:
// Apply to entire server
server.Use(proteus.JsonParser)
// Apply to specific router
router.Use(proteus.JsonParser)
// Apply to specific route
server.Post("/api/users", proteus.JsonParser, func(req *proteus.HttpRequest, res *proteus.HttpResponse) {
userData := req.Body // Contains parsed JSON data
// Process the user data...
})
Requirements:
- Request must have Content-Type: application/json header
- Request body must contain valid JSON
- Content-Length header should be present for best performance
var TextColor = internal.TextColor
TextColor provides utility functions to apply ANSI color codes to text output. This is useful for enhancing the readability of console logs with colored text on terminals that support ANSI escape sequences.
var UrlEncoded = internal.UrlEncoded
UrlEncoded is middleware that automatically parses URL-encoded form data from request payloads and makes the parsed data available in the request's Body field. This middleware is essential for handling HTML form submissions and other application/x-www-form-urlencoded content.
The middleware:
- Checks for Content-Type: application/x-www-form-urlencoded header
- Parses form data from the request body
- Stores parsed data in req.Body as a map[string]interface{}
- Handles multiple values for the same field name
- Supports nested field names using bracket notation (field[subfield])
Usage:
// Apply to entire server
server.Use(proteus.UrlEncoded)
// Apply to specific router
router.Use(proteus.UrlEncoded)
// Apply to specific route
server.Post("/submit-form", proteus.UrlEncoded, func(req *proteus.HttpRequest, res *proteus.HttpResponse) {
formData := req.Body // Contains parsed form data
username := formData["username"]
// Process form data...
})
Requirements:
- Request must have Content-Type: application/x-www-form-urlencoded header
- Request body must contain valid URL-encoded data
- Content-Length header should be present for best performance
Supported form field formats:
- Simple fields: name=value
- Multiple values: hobby=reading&hobby=gaming
- Nested fields: user[name]=john&user[age]=30
Functions ¶
This section is empty.
Types ¶
type File ¶
File represents a single file from the local filesystem that can be accessed through the proteus framework. This is typically used for file upload handling and static file serving functionality.
Common properties accessible:
- Name: Original filename
- Size: File size in bytes
- Content: File content data
type Headers ¶
Headers represents a collection of HTTP headers stored as key-value pairs. It provides methods for getting, setting, and manipulating HTTP headers for both requests and responses. Header names are case-insensitive.
Example usage:
headers.Get("Content-Type")
headers.Set("Authorization", "Bearer token")
type HttpRequest ¶
type HttpRequest = internal.HttpRequest
HttpRequest represents an HTTP request received by the web server. It contains all the information about the incoming request including headers, body, URL parameters, query parameters, and metadata. This type is passed to route handlers and middleware functions as the first parameter.
Key fields accessible through methods:
- Headers: Access request headers
- Body: Parsed request body (requires appropriate middleware)
- Params: URL path parameters and query parameters
- Method: HTTP method (GET, POST, etc.)
- URL: Request URL and path information
type HttpResponse ¶
type HttpResponse = internal.HttpResponse
HttpResponse represents an HTTP response that will be sent back to the client. It provides methods for setting response headers, status codes, and body content. This type is passed to route handlers and middleware functions as the second parameter.
Common methods:
- Status(code): Set the HTTP status code
- Send(data): Send response data
- JSON(data): Send JSON response
- Header(key, value): Set response header
type HttpServer ¶
type HttpServer = internal.HttpServer
HttpServer represents a web server instance that can accept and process incoming HTTP requests. It provides methods for configuring middleware, routing, and starting the server to listen on a specific port and host. Create instances using CreateServer() function.
Example usage:
server := proteus.CreateServer() server.Listen(8080, "localhost")
type Params ¶
Params represents a collection of parameters extracted from HTTP requests. This includes both URL path parameters (e.g., /users/:id) and query string parameters (e.g., ?name=value&page=1). All parameter values are stored as strings.
Example usage:
userID := params.Get("id") // URL parameter
page := params.Get("page") // Query parameter
type Router ¶
Router provides functionality for defining HTTP routes and their associated handlers. It supports HTTP methods (GET, POST, PUT, DELETE, etc.), middleware application, and nested routing. Routers can be mounted on servers or other routers.
Example usage:
router := proteus.CreateRouter()
router.Get("/users", getUsersHandler)
router.Post("/users", createUserHandler)
server.Use(router)
type StatusCode ¶
type StatusCode = internal.StatusCode
StatusCode represents an HTTP status code that can be sent in responses. Use the predefined status code constants (Status200, Status404, etc.) rather than raw integer values for better code readability and type safety.
Example usage:
response.Status(proteus.Status200) response.Status(proteus.Status404)
const ( // 1xx Informational responses - indicate that the request was received and understood Status100 StatusCode = internal.Status100 // Continue Status101 StatusCode = internal.Status101 // Switching Protocols Status102 StatusCode = internal.Status102 // Processing Status103 StatusCode = internal.Status103 // Early Hints // 2xx Success - indicate that the action requested by the client was received, understood, and accepted Status200 StatusCode = internal.Status200 // OK Status201 StatusCode = internal.Status201 // Created Status202 StatusCode = internal.Status202 // Accepted Status203 StatusCode = internal.Status203 // Non-Authoritative Information Status204 StatusCode = internal.Status204 // No Content Status205 StatusCode = internal.Status205 // Reset Content Status206 StatusCode = internal.Status206 // Partial Content Status207 StatusCode = internal.Status207 // Multi-Status Status208 StatusCode = internal.Status208 // Already Reported // 3xx Redirection - indicate that further action needs to be taken by the client to complete the request Status300 StatusCode = internal.Status300 // Multiple Choices Status301 StatusCode = internal.Status301 // Moved Permanently Status302 StatusCode = internal.Status302 // Found Status303 StatusCode = internal.Status303 // See Other Status304 StatusCode = internal.Status304 // Not Modified Status305 StatusCode = internal.Status305 // Use Proxy Status307 StatusCode = internal.Status307 // Temporary Redirect Status308 StatusCode = internal.Status308 // Permanent Redirect // 4xx Client Error - indicate that the client seems to have made an error Status400 StatusCode = internal.Status400 // Bad Request Status401 StatusCode = internal.Status401 // Unauthorized Status402 StatusCode = internal.Status402 // Payment Required Status403 StatusCode = internal.Status403 // Forbidden Status404 StatusCode = internal.Status404 // Not Found Status405 StatusCode = internal.Status405 // Method Not Allowed Status406 StatusCode = internal.Status406 // Not Acceptable Status407 StatusCode = internal.Status407 // Proxy Authentication Required Status408 StatusCode = internal.Status408 // Request Timeout Status409 StatusCode = internal.Status409 // Conflict Status410 StatusCode = internal.Status410 // Gone Status411 StatusCode = internal.Status411 // Length Required Status412 StatusCode = internal.Status412 // Precondition Failed Status413 StatusCode = internal.Status413 // Payload Too Large Status414 StatusCode = internal.Status414 // URI Too Long Status415 StatusCode = internal.Status415 // Unsupported Media Type Status416 StatusCode = internal.Status416 // Range Not Satisfiable Status417 StatusCode = internal.Status417 // Expectation Failed Status421 StatusCode = internal.Status421 // Misdirected Request Status422 StatusCode = internal.Status422 // Unprocessable Entity Status423 StatusCode = internal.Status423 // Locked Status424 StatusCode = internal.Status424 // Failed Dependency Status425 StatusCode = internal.Status425 // Too Early Status426 StatusCode = internal.Status426 // Upgrade Required Status428 StatusCode = internal.Status428 // Precondition Required Status429 StatusCode = internal.Status429 // Too Many Requests Status431 StatusCode = internal.Status431 // Request Header Fields Too Large // 5xx Server Error - indicate that the server failed to fulfill a valid request Status500 StatusCode = internal.Status500 // Internal Server Error Status501 StatusCode = internal.Status501 // Not Implemented Status502 StatusCode = internal.Status502 // Bad Gateway Status503 StatusCode = internal.Status503 // Service Unavailable Status504 StatusCode = internal.Status504 // Gateway Timeout Status505 StatusCode = internal.Status505 // HTTP Version Not Supported Status506 StatusCode = internal.Status506 // Variant Also Negotiates Status507 StatusCode = internal.Status507 // Insufficient Storage Status508 StatusCode = internal.Status508 // Loop Detected Status511 StatusCode = internal.Status511 // Network Authentication Required )
HTTP status codes supported by the proteus web server. These constants provide convenient access to all standard HTTP status codes as defined by IANA HTTP Status Code Registry.
