Skip to content

ecromaneli-golang/http

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

39 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

WebServer

A lightweight and flexible HTTP router for Go, designed to simplify web development with dynamic routing, parameter handling, and intuitive APIs.

Go Reference Go Report Card License: MIT

Introduction

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.

Features

  • 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.

Installation

To install the library, use the following command:

go get github.com/ecromaneli-golang/http

How to Use

Creating a Server

package 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")
}

Async Usage

/* [...] */

    // Start the server
    serverChan := server.ListenAndServe(":8080")

    /* Anything */

    // Wait server stop
    err, ok <-serverChan

/* [...] */

Examples

Example 1: Basic Routing

server.Get("/greet/{name}", func(req *webserver.Request, res *webserver.Response) {
    name := req.Param("name")
    res.WriteText("Hello, " + name + "!")
})

Example 2: Handling Parameters

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))
})

Example 3: Server-Sent Events (SSE)

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()
})

Request API

The Request object provides a unified interface for accessing HTTP request data, including headers, parameters, and body content.

Methods

Headers

  • 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()

Parameters

  • 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

  • Body() []byte
    Returns the raw body of the request.
    Example:
    body := req.Body()

Files

  • 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()

Other

  • IsDone() bool
    Checks if the request has been completed or canceled.
    Example:
    if req.IsDone() {
        return
    }

Response API

The Response object provides a fluent interface for constructing HTTP responses.

Methods

Headers

  • 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(status int) *Response
    Sets the HTTP status code for the response.
    Example:
    res.Status(201)

Writing Content

  • 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"})

Server-Sent Events (SSE)

  • 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")

Rendering Files

  • Render(filePath string)
    Reads a file from the file system and writes it to the response.
    Example:
    res.Render("templates/index.html")

Other

  • NoBody()
    Writes an empty response.
    Example:
    res.Status(204).NoBody()

Author

Created and maintained by ecromaneli-golang.

License

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!

About

Go WebServer

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages