gorbit

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2026 License: MIT Imports: 14 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

gorbit

gorbit Logo

Gorbit is an Express-inspired web framework for Go focused on simplicity, performance, and an intuitive developer experience. It provides routing, middleware, WebSockets, static file serving, and modular APIs without unnecessary abstractions.

Go Version License Status


Contents


Features
  • 🚀 Lightweight with zero unnecessary abstractions
  • ⚡ Fast HTTP router
  • 📦 Modular middleware system
  • 🔌 Built-in WebSocket support
  • 📁 Route mounting
  • 🎯 URL parameters
  • 🔄 Middleware chaining
  • 🧩 Simple and expressive API
  • ❤️ Easy to learn for Node.js developers

Installation

Requires Go 1.26 or newer.

go get github.com/pav-studio/gorbit

Quick Start

package main

import (
    "log"
    gb "github.com/pav-studio/gorbit"
    "github.com/pav-studio/gorbit/middleware"
)

func main() {

    app := gb.New(3000)

    app.Use(middleware.AllowAllCORS())

    app.GET("/", func(c *gb.Ctx) {

        c.OK(gb.JSON{
            "framework": "Gorbit",
            "message":   "Hello, World!",
            "status":    "running",
        })

    })

    app.GET("/hello/:name", func(c *gb.Ctx) {

        c.OK(gb.JSON{
            "message": "Hello, " + c.Param("name") + "!",
        })

    })

    if err := app.Start(); err != nil {
        log.Fatal(err)
    }
}

Run:

go run .

Server:

http://localhost:3000

Context Values

Share data between middleware and handlers during a request.

app.Use(func(c *gb.Ctx) {

	c.Set("userID", 42)

	c.Next()

})

app.GET("/profile", func(c *gb.Ctx) {

	id, _ := c.Get("userID")

	c.OK(gb.JSON{
		"id": id,
	})

})

Routing

Gorbit supports the standard HTTP methods and expressive route definitions with URL parameters.

GET
app.GET("/users", func(c *gb.Ctx) {

	c.OK(gb.JSON{
		"users": []string{
			"Alice",
			"Bob",
		},
	})

})
POST
app.POST("/users", func(c *gb.Ctx) {

	type CreateUserRequest struct {
		Name string `json:"name"`
	}

	var body CreateUserRequest

	if err := c.BindJSON(&body); err != nil {
		c.BadRequest(gb.JSON{
			"error": "Invalid request body",
		})
		return
	}

	c.Created(gb.JSON{
		"name": body.Name,
	})

})
PUT
app.PUT("/users/:id", func(c *gb.Ctx) {

	c.OK(gb.JSON{
		"id":      c.Param("id"),
		"message": "User updated",
	})

})
DELETE
app.DELETE("/users/:id", func(c *gb.Ctx) {

	c.OK(gb.JSON{
		"message": "User deleted",
	})

})

Route Parameters

Route parameters make it easy to capture values directly from the URL.

app.GET("/users/:id", func(c *gb.Ctx) {

	c.OK(gb.JSON{
		"id": c.Param("id"),
	})

})

Request:

GET /users/42

Response:

{
  "id": "42"
}

Middleware

Middleware allows you to intercept requests before they reach your route handlers. Call c.Next() to continue the chain.

Global middleware:

app.Use(middleware.AllowAllCORS())

Custom middleware:

app.Use(func(c *gb.Ctx) {

	log.Println(c.Method(), c.Path())

	c.Next()

})

Router Groups

Organize related endpoints into reusable routers and mount them under a common prefix.

api := gb.NewRouter()

api.GET("/users", func(c *gb.Ctx) {

	c.OK(gb.JSON{
		"users": []string{
			"Alice",
			"Bob",
		},
	})

})

app.Mount("/api", api)

Routes become:

GET /api/users

Router middleware:

api.Use(func(c *gb.Ctx) {

	token := c.Header("Authorization")

	if token == "" {
		c.Unauthorized(gb.JSON{
			"error": "Missing authorization header",
		})
		return
	}

	c.Next()

})

CORS

Gorbit includes configurable CORS middleware for local development and production deployments.

Allow everything:

app.Use(middleware.AllowAllCORS())

Custom configuration:

app.Use(middleware.CORS(
	middleware.CORSOptions{
		AllowOrigins: []string{
			"http://localhost:5173",
		},
		AllowMethods: []string{
			"GET",
			"POST",
		},
		AllowHeaders: []string{
			"Authorization",
			"Content-Type",
		},
		AllowCredentials: true,
		MaxAge: 3600,
	},
))

BindJSON

Automatically decode JSON request bodies into Go structs.

type LoginRequest struct {
    Username string `json:"username"`
    Password string `json:"password"`
}

app.POST("/login", func(c *gb.Ctx) {

    var body LoginRequest

    if err := c.BindJSON(&body); err != nil {
        c.BadRequest(gb.JSON{
            "error": "Invalid JSON",
        })
        return
    }

    c.OK(body)

})

Cookies

Read and write HTTP cookies using built-in helper methods.

c.SetCookieValue("token", token, gb.CookieOptions{
    HttpOnly: true,
    MaxAge:   3600,
})

token, err := c.Cookie("token")
if err != nil {
    c.Unauthorized(gb.JSON{
        "error": "Token missing",
    })
    return
}

File Upload

Handle multipart form uploads with a simple API.

file, err := c.FormFile("image")
if err != nil {
    c.BadRequest(gb.JSON{
        "error": "No file uploaded",
    })
    return
}

if err := file.SaveTo("./uploads/" + file.Filename); err != nil {
    c.InternalServerError(gb.JSON{
        "error": "Failed to save file",
    })
    return
}

c.OK(gb.JSON{
    "filename": file.Filename,
})

Responses

Use built-in response helpers to return common HTTP responses.

c.OK(gb.JSON{
    "message": "Success",
})

c.Created(gb.JSON{
    "id": 42,
})

c.BadRequest(gb.JSON{
    "error": "Invalid request",
})

c.NotFound(gb.JSON{
    "error": "Resource not found",
})

c.InternalServerError(gb.JSON{
    "error": "Something went wrong",
})

Static Files

Serve files from a local directory with a single line.

app.Static("/public", "./public")

A request to /public/logo.png will serve ./public/logo.png.


WebSockets

Create event-driven WebSocket servers using Gorbit's built-in WebSocket manager.

app.WS.Handle("/chat", func(client *gb.WSClient) {

    client.OnConnect(func(c *gb.WSClient) {
        println("Connected")
    })

    client.On("message", func(c *gb.WSClient, data json.RawMessage) {

        c.Emit("message", gb.JSON{
            "text": "Hello from Gorbit!",
        })

    })

    client.OnConnect(func(c *gb.WSClient) {
        c.Join("general")
    })

})

Project Structure

my-api/
├── main.go
├── go.mod
├── controllers/
├── middleware/
├── routes/
│   ├── auth.go
│   ├── users.go
│   └── posts.go
├── services/
├── models/
└── utils/

Documentation

Looking for more?

Resource Description
📚 Documentation https://gorbit.dev/docs
📖 Go Reference https://pkg.go.dev/github.com/pav-studio/gorbit
💻 GitHub https://github.com/pav-studio/gorbit

Examples

The examples/ directory contains complete applications demonstrating common Gorbit use cases.

Example Description
quickstart Basic HTTP server
rest-api RESTful API with routers and middleware
websocket-chat Event-driven WebSocket server
file-upload Multipart file uploads

Contributing

Contributions are welcome.

  1. Fork the repository.
  2. Create a feature branch.
  3. Commit your changes.
  4. Open a Pull Request.

License

This project is licensed under the MIT License.


Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CookieOptions

type CookieOptions struct {
	Path     string
	Domain   string
	MaxAge   int
	Expires  time.Time
	Secure   bool
	HttpOnly bool
	SameSite http.SameSite
}

CookieOptions defines optional settings used when creating cookies.

type Ctx

type Ctx struct {
	Writer  http.ResponseWriter
	Request *http.Request
	Params  map[string]string
	Keys    map[string]any
	// contains filtered or unexported fields
}

Ctx represents the context of the current HTTP request.

It provides access to the request, response writer, route parameters, middleware state, and helper methods for building HTTP responses.

func (*Ctx) Abort

func (c *Ctx) Abort()

Abort stops execution of any remaining middleware or handlers.

func (*Ctx) AbortJSON

func (c *Ctx) AbortJSON(status int, data any)

func (*Ctx) AbortStatus

func (c *Ctx) AbortStatus(status int)

func (*Ctx) BadRequest

func (c *Ctx) BadRequest(v any)

BadRequest sends a 400 Bad Request JSON response.

func (*Ctx) BindJSON

func (c *Ctx) BindJSON(v any) error

func (*Ctx) Body

func (c *Ctx) Body() ([]byte, error)

Body reads and returns the request body.

func (*Ctx) ContentType

func (c *Ctx) ContentType() string

ContentType returns the Content-Type request header.

func (*Ctx) Cookie

func (c *Ctx) Cookie(name string) (string, error)

Cookie returns the value of the named request cookie.

func (*Ctx) Cookies

func (c *Ctx) Cookies() []*http.Cookie

Cookies returns all cookies included in the request.

func (*Ctx) Created

func (c *Ctx) Created(v any)

Created sends a 201 Created JSON response.

func (*Ctx) DeleteCookie

func (c *Ctx) DeleteCookie(name string, options CookieOptions)

DeleteCookie removes the specified cookie from the client.

func (*Ctx) Download

func (c *Ctx) Download(path, filename string)

Download serves a file as an attachment.

The browser will download the file using the provided filename.

func (*Ctx) File

func (c *Ctx) File(path string)

File serves the specified file.

func (*Ctx) FileUpload

func (c *Ctx) FileUpload(name string) (multipart.File, *multipart.FileHeader, error)

It is equivalent to calling Request.FormFile.

func (*Ctx) Forbidden

func (c *Ctx) Forbidden(v any)

Forbidden sends a 403 Forbidden JSON response.

func (*Ctx) Form

func (c *Ctx) Form(key string) string

Form returns the value of the named form field.

It supports both application/x-www-form-urlencoded and multipart/form-data requests.

func (*Ctx) FormFile

func (c *Ctx) FormFile(name string) (*UploadedFile, error)

FormFile returns the uploaded file associated with the given form field.

The returned UploadedFile contains the file stream, metadata, filename, size, and content type.

func (*Ctx) Get

func (c *Ctx) Get(key string) (any, bool)

Set stores a value in the request context.

Stored values are only available during the current request.

func (*Ctx) HTML

func (c *Ctx) HTML(status int, html string)

HTML sends an HTML response with the specified status code.

func (*Ctx) Header

func (c *Ctx) Header(key string) string

Header returns the value of the specified request header.

func (*Ctx) Headers

func (c *Ctx) Headers() http.Header

Headers returns all request headers.

func (*Ctx) Host

func (c *Ctx) Host() string

Host returns the request host.

func (*Ctx) IP

func (c *Ctx) IP() string

IP returns the client's IP address.

It checks X-Forwarded-For and X-Real-IP before falling back to the remote address.

func (*Ctx) InternalServerError

func (c *Ctx) InternalServerError(v any)

InternalServerError sends a 500 Internal Server Error JSON response.

func (*Ctx) JSON

func (c *Ctx) JSON(status int, data any)

JSON sends a JSON response with the specified HTTP status code.

The response Content-Type is automatically set to "application/json".

func (*Ctx) Method

func (c *Ctx) Method() string

Method returns the HTTP request method.

func (*Ctx) Next

func (c *Ctx) Next()

Next executes the next middleware or handler in the chain.

func (*Ctx) NoContent

func (c *Ctx) NoContent()

NoContent sends a 204 No Content response.

func (*Ctx) NotFound

func (c *Ctx) NotFound(v any)

NotFound sends a 404 Not Found JSON response.

func (*Ctx) OK

func (c *Ctx) OK(v any)

OK sends a 200 OK JSON response.

func (*Ctx) Param

func (c *Ctx) Param(name string) string

Param returns the value of the named route parameter.

It returns an empty string if the parameter does not exist.

func (*Ctx) Path

func (c *Ctx) Path() string

Path returns the request URL path.

func (*Ctx) Queries

func (c *Ctx) Queries() map[string][]string

Queries returns all URL query parameters.

func (*Ctx) Query

func (c *Ctx) Query(key string) string

Query returns the value of the named query parameter.

Example:

GET /users?page=2

c.Query("page") // "2"

func (*Ctx) QueryDefault

func (c *Ctx) QueryDefault(key, defaultValue string) string

QueryDefault returns the query parameter value if present, otherwise it returns defaultValue.

func (*Ctx) Redirect

func (c *Ctx) Redirect(status int, url string)

Redirect redirects the client to the provided URL using the specified HTTP status code.

func (*Ctx) Scheme

func (c *Ctx) Scheme() string

Scheme returns "https" when the request is using TLS, otherwise it returns "http".

func (*Ctx) Set

func (c *Ctx) Set(key string, value any)

Set stores a value in the request context.

Stored values are only available during the current request.

func (*Ctx) SetCookie

func (c *Ctx) SetCookie(cookie *http.Cookie)

SetCookie adds the provided cookie to the response.

c.SetCookie(&http.Cookie{
	Name:     "token",
	Value:    jwt,
	Path:     "/",
	HttpOnly: true,
	Secure:   true,
	MaxAge:   3600,
})

func (*Ctx) SetCookieValue

func (c *Ctx) SetCookieValue(
	name string,
	value string,
	options CookieOptions,
)

SetCookieValue creates and sends a cookie using the provided name, value, and options.

func (*Ctx) Status

func (c *Ctx) Status(status int) *Ctx

Status sets the HTTP status code and returns the current context.

This allows method chaining.

func (*Ctx) String

func (c *Ctx) String(status int, message string)

String sends a plain text response with the specified HTTP status code.

func (*Ctx) Unauthorized

func (c *Ctx) Unauthorized(v any)

Unauthorized sends a 401 Unauthorized JSON response.

func (*Ctx) UserAgent

func (c *Ctx) UserAgent() string

UserAgent returns the client's User-Agent header.

type EventHandler

type EventHandler func(*WSClient, json.RawMessage)

EventHandler handles an incoming WebSocket event.

type Handler

type Handler func(*Ctx)

Handler represents an HTTP request handler.

type JSON

type JSON map[string]any

JSON is a convenience type for constructing JSON responses.

Example:

c.JSON(http.StatusOK, gorbit.JSON{
    "message": "Hello",
})

type Packet

type Packet struct {
	Event string          `json:"event"`
	Data  json.RawMessage `json:"data"`
}

Packet represents a WebSocket event packet exchanged between client and server.

type Route

type Route struct {
	Method    string
	Path      string
	Segments  []string
	ParamKeys []string
	Handlers  []Handler
	WebSocket bool
	WSHandler WSHandler
}

Route represents a registered HTTP or WebSocket route.

type Router

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

Router groups routes and middleware that can be mounted onto a Server.

func NewRouter

func NewRouter() *Router

NewRouter creates a new Router.

Routers allow routes and middleware to be grouped before mounting them onto a Server.

func (*Router) DELETE

func (r *Router) DELETE(path string, handlers ...Handler)

DELETE registers a DELETE route.

func (*Router) GET

func (r *Router) GET(path string, handlers ...Handler)

GET registers a GET route.

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, handlers ...Handler)

OPTIONS registers an OPTIONS route.

func (*Router) POST

func (r *Router) POST(path string, handlers ...Handler)

POST registers a POST route.

func (*Router) PUT

func (r *Router) PUT(path string, handlers ...Handler)

PUT registers a PUT route.

func (*Router) Use

func (r *Router) Use(handlers ...Handler)

Use registers middleware for the router.

Router middleware is executed before the route handlers within that router.

type Server

type Server struct {
	WS *WSManager
	// contains filtered or unexported fields
}

Server represents a Gorbit application.

A Server manages routes, middleware, static file serving, and WebSocket endpoints.

func New

func New(port int) *Server

New creates a new Server listening on the specified port.

Example:

app := gorbit.New(8080)

func (*Server) DELETE

func (s *Server) DELETE(path string, handlers ...Handler)

DELETE registers a DELETE route.

func (*Server) GET

func (s *Server) GET(path string, handlers ...Handler)

GET registers a GET route.

func (*Server) Mount

func (s *Server) Mount(prefix string, router *Router)

Mount registers all routes and middleware from the provided router under the specified path prefix.

Example:

api := gorbit.NewRouter()

api.GET("/users", GetUsers)

app.Mount("/api", api)

func (*Server) OPTIONS

func (s *Server) OPTIONS(path string, handlers ...Handler)

OPTIONS registers an OPTIONS route.

func (*Server) POST

func (s *Server) POST(path string, handlers ...Handler)

POST registers a POST route.

func (*Server) PUT

func (s *Server) PUT(path string, handlers ...Handler)

PUT registers a PUT route.

func (*Server) Start

func (s *Server) Start() error

Start starts the HTTP server.

Start blocks until the server stops or returns an error.

Example:

app := gorbit.New(8080)

app.GET("/", func(c *gorbit.Ctx) {
    c.String(200, "Hello, World!")
})

log.Fatal(app.Start())

func (*Server) Static

func (s *Server) Static(prefix, dir string)

Static serves files from dir under the specified URL prefix.

Example:

app.Static("/public", "./public")

func (*Server) Use

func (s *Server) Use(h Handler)

Use registers one or more global middleware handlers.

Registered middleware is executed before route handlers.

type UploadedFile

type UploadedFile struct {
	File   multipart.File
	Header *multipart.FileHeader

	Filename    string
	Size        int64
	ContentType string
}

UploadedFile represents a file uploaded through a multipart/form-data request.

func (*UploadedFile) SaveTo

func (f *UploadedFile) SaveTo(path string) error

SaveTo writes the uploaded file to the specified destination path.

type WSAuthFunc added in v1.2.0

type WSAuthFunc func(*http.Request) error

WSManager manages WebSocket routes, connected clients, rooms, and connection options.

type WSClient

type WSClient struct {
	ID      string
	Conn    *coderws.Conn
	Context context.Context

	// Original HTTP request used to establish this WebSocket.
	//
	// This contains the cookies and headers that were sent during
	// the WebSocket handshake.
	Request *http.Request

	Values map[string]any
	// contains filtered or unexported fields
}

WSClient represents a connected WebSocket client.

func (*WSClient) Close

func (c *WSClient) Close() error

Close gracefully closes the WebSocket connection.

func (*WSClient) Cookie added in v1.2.0

func (c *WSClient) Cookie(name string) (string, error)

Cookie returns a cookie received during the WebSocket handshake.

func (*WSClient) Delete

func (c *WSClient) Delete(key string)

Delete removes a stored value associated with the client.

func (*WSClient) Emit

func (c *WSClient) Emit(event string, data any) error

Emit sends an event and payload to the connected client.

Payload encoding happens before the WebSocket write. The client context is used for the write.

func (*WSClient) EmitJSON

func (c *WSClient) EmitJSON(event string, v any) error

EmitJSON is an alias for Emit.

func (*WSClient) Get

func (c *WSClient) Get(key string) (any, bool)

Get retrieves a value previously stored using Set.

func (*WSClient) Header added in v1.2.0

func (c *WSClient) Header(name string) string

Header returns a request header received during the WebSocket handshake.

func (*WSClient) Join

func (c *WSClient) Join(room string)

Join adds the client to the specified room.

Room membership is protected by the manager mutex.

func (*WSClient) Leave

func (c *WSClient) Leave(room string)

Leave removes the client from the specified room.

Room membership is protected by the manager mutex.

func (*WSClient) LeaveAll

func (c *WSClient) LeaveAll()

LeaveAll removes the client from every room it has joined.

The entire room membership operation is protected by the manager mutex.

func (*WSClient) Listen

func (c *WSClient) Listen()

Listen begins reading incoming WebSocket messages.

func (*WSClient) On

func (c *WSClient) On(event string, handler EventHandler)

On registers a handler for the specified event.

func (*WSClient) OnConnect

func (c *WSClient) OnConnect(fn func(*WSClient))

func (*WSClient) OnDisconnect

func (c *WSClient) OnDisconnect(fn func(*WSClient))

func (*WSClient) Raw

func (c *WSClient) Raw(
	messageType coderws.MessageType,
	data []byte,
) error

func (*WSClient) Set

func (c *WSClient) Set(key string, value any)

Set stores a value associated with the current WebSocket client.

type WSHandler

type WSHandler func(*WSClient)

WSHandler represents a WebSocket connection handler.

type WSManager

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

func WS

func WS() *WSManager

WS returns the application's global WebSocket manager.

It panics if the WebSocket manager has not been initialized.

func (*WSManager) AddOrigins

func (m *WSManager) AddOrigins(origins ...string)

func (*WSManager) AllowAllOrigins

func (m *WSManager) AllowAllOrigins()

func (*WSManager) Auth added in v1.2.0

func (m *WSManager) Auth(fn WSAuthFunc)

Auth sets a function that is executed before accepting every WebSocket connection.

Returning an error rejects the WebSocket handshake.

func (*WSManager) Broadcast

func (m *WSManager) Broadcast(room, event string, data any)

Broadcast sends an event with the provided payload to every client currently joined to the specified room.

The room map is protected against concurrent Join/Leave calls. Network writes happen after releasing the manager lock.

func (*WSManager) Handle

func (m *WSManager) Handle(path string, handler WSHandler)

Handle registers a WebSocket endpoint for the specified path.

func (*WSManager) Options

func (m *WSManager) Options() *coderws.AcceptOptions

func (*WSManager) SetOptions

func (m *WSManager) SetOptions(options coderws.AcceptOptions)

Directories

Path Synopsis
example
rest-api command
Package middleware provides reusable middleware for Gorbit.
Package middleware provides reusable middleware for Gorbit.

Jump to

Keyboard shortcuts

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