web

package module
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2021 License: MIT Imports: 25 Imported by: 1

README

Build Status

web

web is a simple way to write web applications in the Go programming language. It's ideal for writing simple backend web services.

Overview

web is designed to be a lightweight HTTP-Router that makes dependencies clear. Some features include:

  • Function's dependencies clearly visible in signature
  • Routing to url handlers based on regular expressions
  • Handlers can return strings to have them written as the response
  • Secure cookies

Known-Issues

If you're looking for the fastest router, this is probably not your best choice, since it uses the reflect-Package to call the handler functions and regular expressions for matching routes. If speed is your main concern, you're probably better off using something like HttpRouter (also see the Go HTTP Router Benchmark).

Installation

Make sure you have the a working Go environment. See the install instructions. web.go targets the Go release branch.

To install web.go, simply run:

go get github.com/JaCoB1123/web

To compile it from source:

git clone git://github.com/JaCoB1123/web.git
cd web && go build

Example

Parameters in the url are declared using regular expressions. Each group can be referenced by adding a parameter to the handler function.

The following example sets up two routes:

  • The first route requires an integer as the first URL element, which is later passed as the first argument to the handler function helloInt. Anything after that is accepted as a string (including more slashes) and passed as the second argument.
  • The second route accepts anything that doesn't match the first rule as a string and passes that as the only parameter to the handler function hello.
package main

import (
        "fmt"

        "github.com/JaCoB1123/web"
)

func main() {
        web.Get("/([-+]?[0-9]*)/(.*)", helloInt)
        web.Get("/(.*)", hello)
        web.Run("0.0.0.0:9999")
}

// hello requires a single string parameter in the url
func hello(val string) string {
        return "hello " + val + "\n"
}

// hello requires an integer and a string parameter in the url
func helloInt(intval int, val string) string {
    return fmt.Sprintf("hello %s (%d)\n", val, intval)
}

To run the application, put the code in a file called hello.go and run:

go run hello.go

You can point your browser to http://localhost:9999/13/world.

Getting parameters

Route handlers may contain a pointer to web.Context as their first parameter. This variable serves many purposes -- it contains information about the request, and it provides methods to control the http connection. This also allows direct access to the http.ResponseWriter. For instance, to iterate over the web parameters, either from the URL of a GET request, or the form data of a POST request, you can access ctx.Params, which is a map[string]string:

package main

import (
    "github.com/JaCoB1123/web"
)
    
func hello(ctx *web.Context, val string) { 
    for k,v := range ctx.Params {
        println(k, v)
    }
}   
    
func main() {
    web.Get("/(.*)", hello)
    web.Run("0.0.0.0:9999")
}

In this example, if you visit http://localhost:9999/?a=1&b=2, you'll see the following printed out in the terminal:

a 1
b 2

Roadmap

Here's a non-exhaustive list of things I'm planning to add:

  • Simple JSON-handling by returning structs
  • Handling custom types as function-parameters (e.g. using an integer parameter in the URL, but have the function accept a struct, that is loaded from the database)
  • Some performance improvements

About

Based on the awesome web.go project by Michael Hoisie

Documentation

Overview

Package web is a lightweight web framework for Go. It's ideal for writing simple, performant backend web services.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrMissingCookieSecret = errors.New("Secret Key for secure cookies has not been set. Assign one to web.Config.CookieSecret.")
	ErrInvalidKey          = errors.New("The keys for secure cookies have not been initialized. Ensure that a Run* method is being called")
)
View Source
var Config = &ServerConfig{
	RecoverPanic: true,
	ColorOutput:  true,
}

Config is the configuration of the main server.

View Source
var NoValueNeeded = fmt.Errorf("No value needed")
View Source
var NotSupported = fmt.Errorf("Type is not supported")

Functions

func NewCookie added in v0.2.0

func NewCookie(name string, value string, age int64) *http.Cookie

NewCookie is a helper method that returns a new http.Cookie object. Duration is specified in seconds. If the duration is zero, the cookie is permanent. This can be used in conjunction with ctx.SetCookie.

func Slug added in v0.2.0

func Slug(s string, sep string) string

Slug is a helper function that returns the URL slug for string s. It's used to return clean, URL-friendly strings that can be used in routing.

func Urlencode

func Urlencode(data map[string]string) string

Urlencode is a helper method that converts a map into URL-encoded form data. It is a useful when constructing HTTP POST requests.

Types

type Context

type Context struct {
	Request *http.Request
	Params  map[string]string
	Server  *Server
	http.ResponseWriter
}

A Context object is created for every incoming HTTP request, and is passed to handlers as an optional first argument. It provides information about the request, including the http.Request object, the GET and POST params, and acts as a Writer for the response.

func (*Context) Abort

func (ctx *Context) Abort(status int, body string)

Abort is a helper method that sends an HTTP header and an optional body. It is useful for returning 4xx or 5xx errors. Once it has been called, any return value from the handler will not be written to the response.

func (*Context) BadRequest added in v0.2.0

func (ctx *Context) BadRequest()

BadRequest writes a 400 HTTP response

func (*Context) ContentType added in v0.2.0

func (ctx *Context) ContentType(val string) string

ContentType sets the Content-Type header for an HTTP response. For example, ctx.ContentType("json") sets the content-type to "application/json" If the supplied value contains a slash (/) it is set as the Content-Type verbatim. The return value is the content type as it was set, or an empty string if none was found.

func (*Context) Forbidden added in v0.2.0

func (ctx *Context) Forbidden()

Forbidden writes a 403 HTTP response

func (*Context) GetBasicAuth added in v0.2.0

func (ctx *Context) GetBasicAuth() (string, string, error)

GetBasicAuth returns the decoded user and password from the context's 'Authorization' header.

func (*Context) GetSecureCookie

func (ctx *Context) GetSecureCookie(name string) (string, bool)

func (*Context) NotFound

func (ctx *Context) NotFound(message string)

NotFound writes a 404 HTTP response

func (*Context) NotModified added in v0.2.0

func (ctx *Context) NotModified()

Notmodified writes a 304 HTTP response

func (*Context) Redirect

func (ctx *Context) Redirect(status int, url_ string)

Redirect is a helper method for 3xx redirects.

func (*Context) Reset added in v0.5.0

func (ctx *Context) Reset(req *http.Request, s *Server, w http.ResponseWriter)

func (*Context) SetCookie

func (ctx *Context) SetCookie(cookie *http.Cookie)

SetCookie adds a cookie header to the response.

func (*Context) SetHeader added in v0.2.0

func (ctx *Context) SetHeader(hdr string, val string, unique bool)

SetHeader sets a response header. If `unique` is true, the current value of that header will be overwritten . If false, it will be appended.

func (*Context) SetSecureCookie

func (ctx *Context) SetSecureCookie(name string, val string, age int64) error

func (*Context) Unauthorized added in v0.2.0

func (ctx *Context) Unauthorized()

Unauthorized writes a 401 HTTP response

func (*Context) WriteString

func (ctx *Context) WriteString(content string)

WriteString writes string data into the response object.

type Server added in v0.2.0

type Server struct {
	Config *ServerConfig

	Logger       *log.Logger
	Env          map[string]interface{}
	TypeHandlers []typeHandlerDelegate
	// contains filtered or unexported fields
}

Server represents a web.go server.

func NewServer added in v0.2.0

func NewServer() *Server

func (*Server) Delete added in v0.2.0

func (s *Server) Delete(route string, handler interface{})

Delete adds a handler for the 'DELETE' http method for server s.

func (*Server) Get added in v0.2.0

func (s *Server) Get(route string, handler interface{})

Get adds a handler for the 'GET' http method for server s.

func (*Server) Handle added in v0.2.0

func (s *Server) Handle(route string, method string, httpHandler http.Handler)

Add a custom http.Handler

func (*Server) Head added in v0.5.0

func (s *Server) Head(route string, handler interface{})

Head adds a handler for the 'HEAD' http method for server s.

func (*Server) Match added in v0.2.0

func (s *Server) Match(method string, route string, handler interface{})

Match adds a handler for an arbitrary http method for server s.

func (*Server) Post added in v0.2.0

func (s *Server) Post(route string, handler interface{})

Post adds a handler for the 'POST' http method for server s.

func (*Server) Process added in v0.2.0

func (s *Server) Process(c http.ResponseWriter, req *http.Request)

Process invokes the routing system for server s

func (*Server) Put added in v0.2.0

func (s *Server) Put(route string, handler interface{})

Put adds a handler for the 'PUT' http method for server s.

func (*Server) ServeHTTP added in v0.2.0

func (s *Server) ServeHTTP(c http.ResponseWriter, req *http.Request)

ServeHTTP is the interface method for Go's http server package

func (*Server) SetLogger added in v0.2.0

func (s *Server) SetLogger(logger *log.Logger)

SetLogger sets the logger for server s

type ServerConfig added in v0.2.0

type ServerConfig struct {
	StaticDir    string
	Addr         string
	Port         int
	CookieSecret string
	RecoverPanic bool
	Profiler     bool
	ColorOutput  bool
}

ServerConfig is configuration for server objects.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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