cloudy

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2025 License: MIT Imports: 20 Imported by: 0

README

Cloudy

Cloudy is a lightweight, flexible web framework for Go that emphasizes simplicity and productivity. It provides a clean architecture for building web applications with features like routing, sessions, middleware, and more.

Features

  • Simple and intuitive API
  • Built-in session management
  • Flash message support
  • Middleware pipeline
  • Controller-based architecture
  • Easy routing with method mapping

Installation

go get github.com/CloudyKit/cloudy

Quick Start

Below is a basic example of how to set up a Cloudy web application:

Directory Structure
myapp/
├── app/
│   └── app.go
├── cmd/
│   └── server.go
└── controllers/
    └── home.go
Server Entry Point (server.go)
package main

import "github.com/CloudyKit/cloudy-example/app"

func main() {
	app.Kernel.RunServer(":8888")
}
Application Setup (app.go)
package app

import (
	"github.com/CloudyKit/cloudy"
	"github.com/CloudyKit/cloudy-example/controllers"
	"github.com/CloudyKit/cloudy/flash"
	"github.com/CloudyKit/cloudy/session"
)

var Kernel = cloudy.NewKernel()

func init() {
	// Register components
	Kernel.AddComponents(
		&session.Component{
			Manager:       session.DefaultManager,
			CookieOptions: session.DefaultCookieOptions,
		},
		&flash.Component{},
	)

	// Register controllers
	Kernel.AddControllers(
		&controllers.Home{},
	)
	
	// Add middleware
	Kernel.AddMiddlewareFunc(func(ctx *cloudy.Context) {
		ctx.Response.Header().Set("X-Cloudy", "CloudyKit")
	})
}
Controller (home.go)
package controllers

import (
	"github.com/CloudyKit/cloudy"
	"github.com/CloudyKit/cloudy/session"
)

type Home struct {
	Context     *cloudy.Context
	SessionData *session.Session
}

// Mx maps HTTP methods to controller actions
func (h *Home) Mx(mx *cloudy.Mapper) {   
	mx.BindAction("GET", "/", "Index")
}

// Index handles the root path
func (h *Home) Index() {
	counter, _ := h.SessionData.Get("counter").(int)
	_, _ = h.Context.PrintfWriteStringfWriteString("Counter: %d", counter)
	counter++
	defer h.SessionData.Set("counter", counter)
}

Core Concepts

Kernel

The Kernel is the central component that manages the application lifecycle. It handles routing, middleware execution, and component initialization.

Controllers

Controllers handle incoming requests and produce responses. In Cloudy, controllers are Go structs with methods that correspond to HTTP endpoints.

Middleware

Middleware functions can be added to the request processing pipeline to handle cross-cutting concerns like authentication, logging, etc.

Components

Components provide additional functionality like sessions and flash messages. They can be easily added to the application's kernel.

Mapper

The Mapper binds HTTP methods and paths to controller methods, making routing simple and intuitive.

Running the Example

To run the example application:

go run cmd/server.go

Then visit http://localhost:8888 in your browser. You should see a counter that increments on each page refresh, demonstrating the session functionality.

License

[MIT License]

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.'

Documentation

Overview

Package formam implements functions to decode values of a html form.

Index

Constants

View Source
const TAG_NAME = "formam"

Variables

View Source
var ContextType = reflect.TypeOf((*Context)(nil))
View Source
var DefaultKernel = NewKernel()
View Source
var KernelType = reflect.TypeOf((*Kernel)(nil))

Functions

func DispatchNext

func DispatchNext(context *Context, name string, writer http.ResponseWriter, request *http.Request, parameter router.Parameter, registry Registry, handlers []Handler) error

DispatchNext entry point

func Env

func Env(def, key string, fallbacks ...string) string

Env works as GetEnv but the first argument is a default value

func GetEnv

func GetEnv(key string, fallbacks ...string) (value string)

GetEnv same as os.GetEnv, but with fallback support

func LookupEnv

func LookupEnv(Key string, fallbacks ...string) (value string, found bool)

LookupEnv same as os.LookupEnv, but with fallback support

Types

type Component

type Component interface {
	Bootstrap(app *Kernel)
}

Component represents a service component, a component need to implement a bootstrap method which is responsible to set up the component with the app, ex: register a type Providers, or add middleware handler

func NewComponentBundle

func NewComponentBundle(components ...Component) Component

func NewControllerBundle

func NewControllerBundle(controllers ...Controller) Component

NewControllerBundle creates a component that will bind the passed context at bootstrap

type ComponentBundle

type ComponentBundle []Component

func (ComponentBundle) Bootstrap

func (c ComponentBundle) Bootstrap(a *Kernel)

type ComponentFunc

type ComponentFunc func(*Kernel)

ComponentFunc func implementing Component interface

func (ComponentFunc) Bootstrap

func (component ComponentFunc) Bootstrap(a *Kernel)

type Context

type Context struct {
	Name     string        // The name associated with the route
	Registry Registry      // Dependency injection context
	Request  *http.Request // Request data passed by the router
	Gen      *link.URLGen

	Response http.ResponseWriter // Response Writer passed by the router
	Params   router.Parameter    // Route Registry passed by the router
	// contains filtered or unexported fields
}

Context holds context information about the incoming request

func GetContext

func GetContext(cdi Registry) *Context

GetContext gets a Context from the registry context

func (*Context) BindForm

func (c *Context) BindForm(target interface{}) error

BindForm decodes request post data into target

func (*Context) BindGetForm

func (c *Context) BindGetForm(target interface{}) error

BindGetForm decodes the request url values into target

func (*Context) BindJSON

func (c *Context) BindJSON(target interface{}) error

BindJSON decodes request body as json into the target

func (*Context) GetBodyBytes

func (c *Context) GetBodyBytes() ([]byte, error)

func (*Context) GetBodyReader

func (c *Context) GetBodyReader() io.ReadCloser

GetBodyReader returns bytes bodyReader

func (*Context) GetCookieValue

func (c *Context) GetCookieValue(name string) (value string)

GetCookieValue returns a cookie value from the request

func (*Context) GetGetValue

func (c *Context) GetGetValue(name string) string

GetGetValue returns a form value from the request, GetPostValue is shortcut for Context.Request.Form.Get method

func (*Context) GetPostValue

func (c *Context) GetPostValue(name string) string

GetPostValue returns a form value from the request, GetPostValue is shortcut for Context.Request.Form.Get method

func (*Context) GetURLParameter

func (c *Context) GetURLParameter(name string) string

GetURLParameter returns a parameter from the url route, GetURLParameter is shortcut for Context.Params.Get method

func (*Context) GoContext

func (c *Context) GoContext() context.Context

func (*Context) Next

func (c *Context) Next() error

Next will continue with the request flow

func (*Context) Printf

func (c *Context) Printf(format string, v ...interface{}) (int, error)

Printf prints a formatted text to response writer

func (*Context) Redirect

func (c *Context) Redirect(urlStr string)

Redirect redirects the request to the specified urlStr and send a http StatusFound code

func (*Context) RedirectStatus

func (c *Context) RedirectStatus(urlStr string, httpStatus int)

RedirectStatus redirects the request to the specified urlStr and send the the status code specified by httpStatus

func (*Context) SendJSON

func (c *Context) SendJSON(v any) error

func (*Context) SendJSONWithStatus added in v1.0.2

func (c *Context) SendJSONWithStatus(v any, statusCode int) error

func (*Context) SendTextWithStatus

func (c *Context) SendTextWithStatus(statusCode int, content string) error

func (*Context) WriteString

func (c *Context) WriteString(txt string) (int, error)

WriteString writes the string txt into the the response

type Controller

type Controller interface {
	Mx(*Mapper)
}

type ControllerBundle

type ControllerBundle []Controller

func (ControllerBundle) Bootstrap

func (c ControllerBundle) Bootstrap(a *Kernel)

type ControllerURLGen

type ControllerURLGen struct {
	Parent link.URLGen
	// contains filtered or unexported fields
}

func (*ControllerURLGen) URL

func (urlGen *ControllerURLGen) URL(dst string, v ...interface{}) string

type Handler

type Handler interface {
	Handle(*Context)
}

Handler is responsible to handle the request or part of the request, ex: a middleware handler would process some data put the data into the scope.registry and invoke DispatchNext which will invoke the next handler, the last handler is responsible for the main logic of the request. calling DispatchNext in the last handler will panic.

type HandlerFunc

type HandlerFunc func(*Context)

HandlerFunc func implementing Handler interface

func (HandlerFunc) Handle

func (fn HandlerFunc) Handle(c *Context)

type Kernel

type Kernel struct {
	Registry Registry       // Kernel Registry dependency injection context
	Router   *router.Router // Router
	Prefix   string         // Prefix prefix for path added in this app
	URLGen   MapURLGen
	MiddlewareBundle
	// contains filtered or unexported fields
}

Kernel app holds your top level data for you service

Router, Dispatcher, Scope

func GetKernel

func GetKernel(c Registry) *Kernel

func NewKernel

func NewKernel() *Kernel

func (*Kernel) AddComponents

func (kernel *Kernel) AddComponents(b ...Component)

AddComponents bootstraps a list of components, a sub scope will be created, and a copy of the original app is used, in such form that modifying the app.Prefix will not reflect outside this call.

func (*Kernel) AddControllers

func (kernel *Kernel) AddControllers(contexts ...Controller)

func (*Kernel) AddHandler

func (kernel *Kernel) AddHandler(method, path string, handler Handler, filters ...Handler)

AddHandler register a handler, see: Handler

func (*Kernel) AddHandlerContextName

func (kernel *Kernel) AddHandlerContextName(registry Registry, name, method, path string, handler Handler, filters ...Handler)

AddHandlerContextName accepts a context, a ParamKey identifier, http method|methods, pattern path, handler and handlers ex: one handler app.AddHandlerContextName(myContext,"mySectionIdentifier","GET", "/public",fileServer,checkAuth)

multiples handles app.AddHandlerContextName(myContext,"mySectionIdentifier","GET|POST|SEARCH", "/products",productHandler,checkAuth)

func (*Kernel) AddHandlerFunc

func (kernel *Kernel) AddHandlerFunc(method, path string, fn HandlerFunc, filters ...Handler)

AddHandlerFunc register a func handler, see: Handler

func (*Kernel) AddHandlerName

func (kernel *Kernel) AddHandlerName(name, method, path string, handler Handler, filters ...Handler)

AddHandlerName register a named handler, see: Handler

func (*Kernel) Container

func (kernel *Kernel) Container() Registry

func (*Kernel) Dispatch

func (kernel *Kernel) Dispatch(eventName string, payload event.Payload)

func (*Kernel) Dispose

func (kernel *Kernel) Dispose()

Dispose Close same as app.registry.Close() invoke this func before exiting the app to cleanup

func (*Kernel) Fork

func (kernel *Kernel) Fork() *Kernel

Fork create child app

func (*Kernel) MustDispose

func (kernel *Kernel) MustDispose()

func (*Kernel) Root

func (kernel *Kernel) Root() *Kernel

Root returns the root app

func (*Kernel) RunServer

func (kernel *Kernel) RunServer(host string) error

RunServer runs the server with the specified host Calling this func will emit a "app.run" event in the app

func (*Kernel) RunServerTLS

func (kernel *Kernel) RunServerTLS(host, certfile, keyfile string) error

RunServerTLS runs the server in tls mode Calling this func will emit a "app.run.tls" event in the app

func (*Kernel) Snapshot

func (kernel *Kernel) Snapshot() *Kernel

Snapshot causes a sub app to be created and inserted in the scope calling app.Root will return the created sub app

func (*Kernel) Subscribe

func (kernel *Kernel) Subscribe(eventName string, handler interface{})

type MapURLGen

type MapURLGen map[string]string

func (MapURLGen) URL

func (urlGen MapURLGen) URL(dst string, v ...interface{}) string

type Mapper

type Mapper struct {
	Prefix string
	Name   string

	Registry Registry

	*ControllerURLGen

	MiddlewareBundle
	// contains filtered or unexported fields
}

func (*Mapper) BindAction

func (mx *Mapper) BindAction(method, path, action string, filters ...Handler)

type MiddlewareBundle

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

func (*MiddlewareBundle) AddMiddleware

func (filterHandlers *MiddlewareBundle) AddMiddleware(filters ...Handler)

AddMiddleware adds handlers to the request chain

func (*MiddlewareBundle) AddMiddlewareFunc

func (filterHandlers *MiddlewareBundle) AddMiddlewareFunc(filters ...HandlerFunc)

func (*MiddlewareBundle) ClearMiddlewares

func (filterHandlers *MiddlewareBundle) ClearMiddlewares()

ClearMiddlewares will clear the registered middlewares for next route added

type Registry

type Registry = registry.Interface

type RunServerEvent

type RunServerEvent struct {
	event.Event
	Host string
	Port string
}

type RunServerEventTLS

type RunServerEventTLS struct {
	event.Event
	Host     string
	CertFile string
	KeyFile  string
}

Directories

Path Synopsis
utils

Jump to

Keyboard shortcuts

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