A lightweight and flexible HTTP router for Go, designed to simplify web development with dynamic routing, parameter handling, and intuitive APIs.
WebServer is a Go-based HTTP router that provides dynamic URL pattern matching, unified parameter collection, and a clean API for building web applications. It supports features like wildcard routing, optional parameters, and server-sent events (SSE), making it a powerful tool for creating modern web services.
- Dynamic Routing: Supports wildcards (
*,**), named parameters ({name}), and optional parameters ({name?}). - Unified Parameter Handling: Access path, query, and body parameters seamlessly.
- Server-Sent Events (SSE): Built-in support for real-time updates.
- Static File Serving: Serve static files with ease.
- Fluent Response API: Chainable methods for setting headers, status codes, and writing responses.
To install the library, use the following command:
go get github.com/ecromaneli-golang/httppackage main
import (
"github.com/ecromaneli-golang/http/webserver"
)
func main() {
// Create a new server instance
server := webserver.NewServer()
// Add routes
server.Get("/hello/{name}", func(req *webserver.Request, res *webserver.Response) {
name := req.Param("name")
res.WriteText("Hello, " + name + "!")
})
// Start the server and wait
server.ListenAndServe(":8080")
}/* [...] */
// Start the server
serverChan := server.ListenAndServe(":8080")
/* Anything */
// Wait server stop
err, ok <-serverChan
/* [...] */server.Get("/greet/{name}", func(req *webserver.Request, res *webserver.Response) {
name := req.Param("name")
res.WriteText("Hello, " + name + "!")
})server.Post("/submit", func(req *webserver.Request, res *webserver.Response) {
name := req.Param("name")
age := req.IntParam("age")
res.WriteText("Received name: " + name + ", age: " + strconv.Itoa(age))
})server.Get("/events", func(req *webserver.Request, res *webserver.Response) {
res.Headers(webserver.EventStreamHeader)
event := &webserver.Event{
Name: "update",
Data: map[string]string{"message": "Hello, SSE!"},
}
res.FlushEvent(event)
// Keep-Alive
<-req.Context().Done()
})The Request object provides a unified interface for accessing HTTP request data, including headers, parameters, and body content.
-
Header(name string) string
Returns the first value of the specified header.
Example:userAgent := req.Header("User-Agent")
-
Headers(name string) []string
Returns all values of the specified header.
Example:cookies := req.Headers("Cookie")
-
AllHeaders() http.Header
Returns all headers as a map.
Example:headers := req.AllHeaders()
-
Param(name string) string
Returns the first value of the specified parameter (path, query, or body).
Example:id := req.Param("id")
-
Params(name string) []string
Returns all values of the specified parameter.
Example:tags := req.Params("tags")
-
AllParams() map[string][]string
Returns all parameters as a map.
Example:params := req.AllParams()
-
UIntParam(name string) uint
Converts the parameter value to an unsigned integer.
Example:age := req.UIntParam("age")
-
IntParam(name string) int
Converts the parameter value to an integer.
Example:count := req.IntParam("count")
-
Float64Param(name string) float64
Converts the parameter value to a 64-bit floating-point number.
Example:price := req.Float64Param("price")
Body() []byte
Returns the raw body of the request.
Example:body := req.Body()
-
File(name string) *multipart.FileHeader
Returns the first uploaded file for the specified form field.
Example:file := req.File("profilePicture")
-
Files(name string) []*multipart.FileHeader
Returns all uploaded files for the specified form field.
Example:files := req.Files("attachments")
-
AllFiles() map[string][]*multipart.FileHeader
Returns all uploaded files as a map.
Example:allFiles := req.AllFiles()
IsDone() bool
Checks if the request has been completed or canceled.
Example:if req.IsDone() { return }
The Response object provides a fluent interface for constructing HTTP responses.
-
Header(key, value string) *Response
Adds a header to the response.
Example:res.Header("Content-Type", "application/json")
-
Headers(headers map[string][]string) *Response
Adds multiple headers to the response.
Example:res.Headers(map[string][]string{ "X-Custom-Header": {"Value1", "Value2"}, })
Status(status int) *Response
Sets the HTTP status code for the response.
Example:res.Status(201)
-
Write(data []byte)
Writes binary data to the response.
Example:res.Write([]byte("Hello, world!"))
-
WriteText(text string)
Writes plain text to the response.
Example:res.WriteText("Hello, world!")
-
WriteJSON(value any)
Serializes the value to JSON and writes it to the response.
Example:res.WriteJSON(map[string]string{"message": "Success"})
-
FlushEvent(event *Event) error
Sends a server-sent event and flushes it immediately.
Example:event := &webserver.Event{ Name: "update", Data: map[string]string{"message": "Hello, SSE!"}, } res.FlushEvent(event)
-
FlushText(text string) error
Writes text to the response and flushes it immediately.
Example:res.FlushText("Real-time update")
Render(filePath string)
Reads a file from the file system and writes it to the response.
Example:res.Render("templates/index.html")
NoBody()
Writes an empty response.
Example:res.Status(204).NoBody()
Created and maintained by ecromaneli-golang.
This project is licensed under the MIT License. See the LICENSE file for details.
Feel free to contribute to this project by submitting issues or pull requests!