coco

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2023 License: MIT Imports: 25 Imported by: 0

README

Coco Web Framework for Go

Coco is a lightweight web framework for Go designed to simplify web application development in go and make it more enjoyable.

Features

  • Routing: Easily define and manage HTTP routes using an expressive routing mechanism.
  • Middleware: Create and apply middleware functions to process requests and responses at various stages of your application.
  • Template Rendering: Coco supports HTML template rendering, allowing you to generate dynamic HTML pages effortlessly.
  • Customizable Settings: Configure settings for your application, such as trust proxy, environment mode, and more.
  • Error Handling: Handle errors and exceptions in a clean and structured manner.
  • Request and Response: Access detailed information about incoming requests and control outgoing responses.
  • JSON and Form Data Parsing: Simplify JSON and form data parsing with built-in functionality.
  • HTTP Range Handling: Conveniently process HTTP ranges for serving partial content.
  • Accept Header Parsing: Determine the best response format based on the incoming request's Accept header.

Getting Started

  1. Installation: To use Coco in your Go project, you need to install it using Go modules:

    go get github.com/tobolabs/coco
    
  2. Creating a Coco App: Import the coco package and create a Coco application:

    package main
    
    import (
        "context"
        "github.com/tobolabs/coco"
    )
    
    func main() {
        app := coco.NewApp()
    
        // Define routes and handlers here
    
        // Start the server
        app.Listen(":8080", context.Background())
    }
    
  3. Routing: Define your routes and handlers using the Get, Post, and other methods provided by Coco. Here's an example:

    app.Get("/", func(res coco.Response, req *coco.Request, next coco.NextFunc) {
        res.Send("Hello, Coco!")
    })
    
  4. Middleware: Apply middleware functions to your routes to add pre or post-processing logic to your requests. Middleware functions are executed in the order they are defined.

    app.Use(func(res coco.Response, req *coco.Request, next coco.NextFunc) {
        // Add middleware logic here
        next(res, req)
    })
    
  5. Request and Response Handling: Access request and response information within your handlers using the Request and Response objects. For example, get query parameters, set headers, or send responses:

    app.Get("/user", func(res coco.Response, req *coco.Request, next coco.NextFunc) {
        username := req.Query["username"]
        res.JSON(map[string]string{"message": "Hello, " + username})
    })
    
  6. Template Rendering: Coco supports HTML template rendering. You can render dynamic HTML pages using Go templates:

    app.Get("/about", func(res coco.Response, req *coco.Request, next coco.NextFunc) {
        data := struct {
            Title   string
            Content string
        }{
            Title:   "About Us",
            Content: "We are Coco, a lightweight web framework for Go.",
        }
        res.Render("about", data)
    })
    

See examples for more.

Configuration

Coco allows you to configure settings for your application. Common configurations include enabling trust proxy, specifying the environment mode, and more. You can use these settings to customize your application behavior.

app.Enable("trust proxy")
app.SetX("env", "production")

Error Handling

Coco provides a structured way to handle errors, including error codes and descriptive error messages. Errors are returned as JSONError and can be handled uniformly in your application.

err := app.Listen(":8080")
if err != nil {
    log.Fatalf("Server failed to start: %v", err)
}

Contributing

Coco is an open-source project, and we welcome contributions from the community. If you'd like to contribute, please check the Contribution Guidelines.

License

Coco is licensed under the MIT License.

Getting Help

If you encounter issues or have questions about Coco, please check the GitHub Issues for known problems or open a new issue.

Roadmap

Check the GitHub repository for the latest updates and the roadmap for Coco.

Acknowledgments

Coco is inspired by Express, a popular web framework for Node.js. At the core of Coco is httprouter, a fast HTTP router for Go by Julien Schmidt.

Authors

Happy coding with Coco! 🌴🚀

GitHub Repository

License

Coco Web Framework for Go

Documentation

Index

Constants

View Source
const (
	GET allowedMethod = 1 << iota
	POST
	PUT
	DELETE
	PATCH
	OPTIONS
	HEAD
)

Variables

View Source
var (
	ErrDirPath      = errors.New("specified path is a directory")
	ErrDotfilesDeny = errors.New("serving dotfiles is not allowed")
)
View Source
var VaryFieldNameRegex = regexp.MustCompile(`^[!#$%&'*+\-.^_` + "`" + `|~0-9A-Za-z]+$`)

VaryFieldNameRegex checks for valid field names for the Vary header as defined by RFC 7231.

Functions

This section is empty.

Types

type App

type App struct {
	*Route // default Route
	// contains filtered or unexported fields
}

App is the main type for the coco framework.

func NewApp

func NewApp() (app *App)

NewApp creates a new App instance with a default Route at the root path "/" and a default settings instance with default values. Equivalent to:

const app = express()

func (*App) Close

func (a *App) Close() error

Close stops the server gracefully and returns any encountered error.

func (*App) Disable

func (a *App) Disable(key string)

Disable sets a setting to false.

func (*App) Disabled

func (a *App) Disabled(key string) bool

Disabled checks if a setting is false.

func (*App) Enable

func (a *App) Enable(key string)

Enable sets a setting to true.

func (*App) Enabled

func (a *App) Enabled(key string) bool

Enabled checks if a setting is true.

func (*App) GetHandler

func (a *App) GetHandler() http.Handler

GetHandler returns the http.Handler for the App.

func (*App) GetX

func (a *App) GetX(key string) interface{}

GetX retrieves a custom setting by its key.

func (*App) IsTrustProxyEnabled

func (a *App) IsTrustProxyEnabled() bool

func (*App) Listen

func (a *App) Listen(addr string) error

Listen starts an HTTP server and listens on the given address. Equivalent to:

app.listen(3000, () => {})

func (*App) LoadTemplates

func (a *App) LoadTemplates(fs fs.FS, config *TemplateConfig) (err error)

LoadTemplates loads templates from an fs.FS with a given config

func (*App) ServeHTTP

func (a *App) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*App) SetX

func (a *App) SetX(key string, value interface{})

SetX sets a custom setting with a key and value.

func (*App) Settings

func (a *App) Settings() map[string]interface{}

Settings returns the settings instance for the App.

type Body

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

func (*Body) FormData

func (body *Body) FormData() (map[string][]string, error)

FormData returns the body form data, expects request sent with `x-www-form-urlencoded` header or

func (*Body) JSON

func (body *Body) JSON(dest interface{}) error

JSON marshals the request body into the given interface. It returns an error if the request body is not a valid JSON or if the given interface is not a pointer.

func (*Body) Text

func (body *Body) Text() (string, error)

Text returns the request body as a string.

type DownloadOption

type DownloadOption struct {
	MaxAge       int
	LastModified bool
	Headers      map[string]string
	Dotfiles     string
	AcceptRanges bool
	CacheControl bool
	Immutable    bool
}

type Error

type Error struct {
	Code    int
	Message string
}

Error is an error type that is returned when an error occurs while handling a request.

func (Error) Error

func (e Error) Error() string

type Handler

type Handler func(res Response, req *Request, next NextFunc)

Handler Handle is a function that is called when a request is made to the Route.

type JSONError

type JSONError struct {
	Status  int
	Message string
}

JSONError is an error type that is returned when the request body is not a valid JSON.

func (JSONError) Error

func (e JSONError) Error() string

type NextFunc

type NextFunc func(res Response, r *Request)

NextFunc is a function that is called to pass execution to the next handler in the chain.

type ParamHandler

type ParamHandler func(res Response, req *Request, next NextFunc, param string)

ParamHandler is a function that is called when a parameter is found in the Route path.

type Path

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

Path is a type that represents a path in the application.

type Range

type Range struct {
	Start int64
	End   int64
}

Range represents a byte range.

type Request

type Request struct {
	BaseURL string

	// HostName contains the hostname derived from the Host HTTP header.
	HostName string

	// Ip contains the remote IP address of the request.
	Ip string

	// Ips contains the remote IP addresses from the X-Forwarded-For header.
	Ips []string

	// Protocol contains the request protocol string: "http" or "https"
	Protocol string

	// Secure is a boolean that is true if the request protocol is "https"
	Secure bool

	// Subdomains is a slice of subdomain strings.
	Subdomains []string

	// Xhr is a boolean that is true if the request's X-Requested-With header
	// field is "XMLHttpRequest".
	Xhr bool

	// OriginalURL is the original URL requested by the client.
	OriginalURL *url.URL

	// Cookies contains the cookies sent by the request.
	Cookies map[string]string

	// Body contains the body of the request.
	Body

	// Query contains the parsed query string from the URL.
	Query map[string]string

	// Params contains the Route parameters.
	Params map[string]string

	// SignedCookies contains the signed cookies sent by the request.
	SignedCookies map[string]string

	// Stale is a boolean that is true if the request is stale, false otherwise.
	Stale bool

	// Fresh is a boolean that is true if the request is fresh, false otherwise.
	Fresh bool

	// Method contains a string corresponding to the HTTP method of the request:
	// GET, POST, PUT, and so on.
	Method string

	// Path contains a string corresponding to the path of the request.
	Path string
	// contains filtered or unexported fields
}

func (*Request) Context

func (req *Request) Context() coreContext.Context

func (*Request) Cookie

func (req *Request) Cookie(name string) (value string, exists bool)

func (*Request) Get

func (req *Request) Get(name string, defaultValue string) string

Get returns the value of param `name` when present or `defaultValue`.

func (*Request) Is

func (req *Request) Is(mime string) bool

Is returns true if the incoming request’s “Content-Type” HTTP header field matches the given mime type.

func (*Request) Range

func (req *Request) Range(size int64) ([]Range, error)

Range returns the first range found in the request’s “Range” header field. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range

type Response

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

func (*Response) Append

func (r *Response) Append(key, value string) *Response

Append sets the specified value to the HTTP response header field. If the header is not already set, it creates the header with the specified value.

func (*Response) Attachment

func (r *Response) Attachment(filename string) *Response

Attachment sets the Content-Disposition header to “attachment”. If a filename is given, then the Content-Type header is set based on the filename’s extension.

func (*Response) ClearCookie

func (r *Response) ClearCookie(name string) *Response

ClearCookie clears the cookie by setting the MaxAge to -1

func (*Response) Cookie

func (r *Response) Cookie(cookie *http.Cookie) *Response

Cookie sets cookie name to value

func (*Response) Download

func (r *Response) Download(filepath, filename string, options *DownloadOption, cb func(error))

Download transfers the file at the given path. Sets the Content-Type response HTTP header field based on the filename’s extension.

func (*Response) Get

func (r *Response) Get(key string) string

Get returns the HTTP response header specified by field.

func (*Response) JSON

func (r *Response) JSON(v interface{}) *Response

JSON sends a JSON response with the given payload.

func (*Response) Location

func (r *Response) Location(path string) *Response

Location sets the response Location HTTP header to the specified path parameter.

func (*Response) Redirect

func (r *Response) Redirect(path string, status ...int) *Response

Redirect redirects to the URL derived from the specified path, with specified status.

func (*Response) Render

func (r *Response) Render(name string, data interface{}) *Response

Render renders a template with data and sends a text/html response.

func (*Response) Send

func (r *Response) Send(body interface{}) *Response

Send sends the HTTP response.

func (*Response) SendFile

func (r *Response) SendFile(filePath, fileName string, options *DownloadOption, cb func(error))

SendFile transfers the file at the given path. Sets the Content-Type response HTTP header field based on the filename’s extension.

func (*Response) SendStatus

func (r *Response) SendStatus(statusCode int) *Response

SendStatus sends the HTTP response status code.

func (*Response) Set

func (r *Response) Set(key string, value string) *Response

Set sets the specified value to the HTTP response header field.

func (*Response) SignedCookie

func (r *Response) SignedCookie(cookie *http.Cookie, secret string) *Response

SignedCookie SecureCookie sets a signed cookie

func (*Response) Status

func (r *Response) Status(code int) *Response

Status sets the HTTP status for the response.

func (*Response) Type

func (r *Response) Type(filename string) *Response

Type sets the Content-Type HTTP header to the MIME type as determined by the filename’s extension.

func (*Response) Vary

func (r *Response) Vary(field string) *Response

Vary adds a field to the Vary header, if it doesn't already exist.

type Route

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

Route is a type that represents a route in the application. It is equivalent to an express.Router instance.

func (*Route) All

func (r *Route) All(path string, handlers ...Handler) *Route

func (*Route) Delete

func (r *Route) Delete(path string, handlers ...Handler) *Route

func (*Route) Get

func (r *Route) Get(path string, handlers ...Handler) *Route

func (*Route) Head

func (r *Route) Head(path string, handlers ...Handler)

func (*Route) Options

func (r *Route) Options(path string, handlers ...Handler)

func (*Route) Param

func (r *Route) Param(param string, handler ParamHandler)

Param calls the given handler when the route param matches the given param.

func (*Route) Patch

func (r *Route) Patch(path string, handlers ...Handler)

func (*Route) Path

func (r *Route) Path() string

func (*Route) Post

func (r *Route) Post(path string, handlers ...Handler)

func (*Route) Put

func (r *Route) Put(path string, handlers ...Handler)

func (*Route) Router

func (r *Route) Router(path string) *Route

Router is equivalent of app.route(path), returns a new instance of Route

func (*Route) Static

func (r *Route) Static(root fs.FS, path string)

func (*Route) Use

func (r *Route) Use(middleware ...Handler) *Route

Use adds middleware to the route.

type TemplateConfig

type TemplateConfig struct {
	// The file extension of the templates.
	// Defaults to ".html".
	Ext string

	// The directory where the includes are stored.
	// Defaults to "includes".
	IncludesDir string

	// The name used for layout templates :- templates that wrap other contents.
	// Defaults to "layouts".
	Layout string
}

TemplateConfig is a configuration for loading templates from an fs.FS

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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