webWorkers

package module
v0.0.0-...-5287ac3 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2016 License: MIT Imports: 14 Imported by: 0

README

webWorkers GoDoc Status

webWorkers is a library which allows you to serve simple HTTP requests.

Usage

package main

import (
	"fmt"
	"time"

	"github.com/itsmontoya/webWorkers"
)

func main() {
	var (
		ww  *webWorkers.Webworkers
		err error
	)

	if ww, err = webWorkers.New(webWorkers.Opts{
		WorkerCap: 4,
		QueueLen:  128,
		Address: ":8080",
	}, Handle); err != nil {
		panic(err)
	}

	fmt.Println("About to listen")
	ww.Listen()
}

// Handle will handle HTTP requests
func Handle(res *webWorkers.Response, req *webWorkers.Request) {
	res.StatusCode(200)
	res.ContentType("application/json")
	res.Write([]byte(`{ "greeting" : "Hello world!" }`))
}

Benchmarks

go test --bench=BenchmarkPara. --count 4 --benchtime 4s
PASS
BenchmarkParaWWBasic-4            100000             59968 ns/op           14694 B/op        108 allocs/op
BenchmarkParaWWBasic-4            100000             61405 ns/op           14696 B/op        109 allocs/op
BenchmarkParaWWBasic-4            100000             59727 ns/op           14694 B/op        108 allocs/op
BenchmarkParaWWBasic-4            100000             59902 ns/op           14695 B/op        108 allocs/op
BenchmarkParaStdlibBasic-4        200000            128350 ns/op            6032 B/op         61 allocs/op
BenchmarkParaStdlibBasic-4         10000            662088 ns/op            5815 B/op         60 allocs/op
BenchmarkParaStdlibBasic-4         20000            738417 ns/op            6152 B/op         62 allocs/op
BenchmarkParaStdlibBasic-4         10000            436768 ns/op            5326 B/op         58 allocs/op

Documentation

Index

Constants

View Source
const (
	// StatusOK represents the "OK" status
	StatusOK = 200
	// StatusCreated represents the "Created" status
	StatusCreated = 201
	// StatusAccepted represents the "Accepted" status
	StatusAccepted = 202
	// StatusNoContent represents the "No Content" status
	StatusNoContent = 204
	// StatusResetContent represents the "Reset Content" status
	StatusResetContent = 205
	// StatusPartialContent represents the "Partial Content" status
	StatusPartialContent = 206
)

Successful 2xx This class of status code indicates that the client's request was successfully received, understood, and accepted.

View Source
const (
	// StatusMovedPerminantly represents the "Multiple Choices" status
	StatusMultipleChoices = 300
	// StatusMovedPerminantly represents the "Moved Perminantly" status
	StatusMovedPerminantly = 301
	// StatusFound represents the "Found" status
	StatusFound = 302
	// StatusSeeOther represents the "See Other" status
	StatusSeeOther = 303
	// StatusNotModified represents the "Not Modified" status
	StatusNotModified = 304
	// StatusUseProxy represents the "Use Proxy" status
	StatusUseProxy = 306
	// StatusMovedTemporarily represents the "Moved Temporarily" status
	StatusMovedTemporarily = 307
)

Redirection 3xx This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request.

View Source
const (
	// StatusBadRequest represents the "Bad Request" status
	StatusBadRequest = 400
	// StatusUnauthorized represents the "Unauthorized" status
	StatusUnauthorized = 401
	// StatusPaymentRequired represents the "Payment Required" status
	StatusPaymentRequired = 402
	// StatusForbidden represents the "Forbidden" status
	StatusForbidden = 403
	// StatusNotFound represents the "Not Found" status
	StatusNotFound = 404
	// StatusMethodNotAllowed represents the "Method Not Allowed" status
	StatusMethodNotAllowed = 405
	// StatusNotAcceptable represents the "Not Acceptable" status
	StatusNotAcceptable = 406
	// StatusProxyAuthRequired represents the "Proxy Authentication Required" status
	StatusProxyAuthRequired = 407
	// StatusRequestTimeout represents the "Request Timeout" status
	StatusRequestTimeout = 408
	// StatusConflict represents the "Conflict" status
	StatusConflict = 409
	// StatusLengthRequired represents "Lenght Required" status
	StatusLengthRequired = 411
	// StatusRequestEntityTooLarge represents the "Request Entity Too Large" status
	StatusRequestEntityTooLarge = 413
	// StatusRequestURITooLong represents the "Request-URI Too Long" status
	StatusRequestURITooLong = 414
	// StatusUnsupportedMediaType represents the "Unsupported Media Type" status
	StatusUnsupportedMediaType = 415
	// StatusExpectationFailed represents the "Expectation Failed" status
	StatusExpectationFailed = 417
	// StatusTeapot represents when a server is a tea pot.. short and stout.
	StatusTeapot = 418
)

Client Error 4xx This class of status code is intended for cases in which the client seems to have erred.

View Source
const (
	// StatusInternalServerError represents the "Internal Server Error" status
	StatusInternalServerError = 500
	// StatusNotImplemented represents the "Not Implemented" status
	StatusNotImplemented = 501
	// StatusBadGateway represents the "Bad Gateway" status
	StatusBadGateway = 502
	// StatusServiceUnavailable represents the "Service Unavailable" status
	StatusServiceUnavailable = 503
	// StatusGatewayTimeout represents the "Gateway Timeout" status
	StatusGatewayTimeout = 504
	// StatusHTTPVersionUnsupported represents the "HTTP Version Unsupported" status
	StatusHTTPVersionUnsupported = 505
)

Server Error 5xx This class of status code is intended for cases in which the server is aware that it has erred or is incapable of performing the request.

View Source
const (
	// ErrEmptyWorkers is returned when workerCap is set to 0 (or ignored)
	ErrEmptyWorkers = errors.Error("worker capacity must be greater than zero")

	// ErrEmptyQueue is returned when queueLen is set to 0 (or ignored)
	ErrEmptyQueue = errors.Error("queue length must be greater than zero")

	// ErrIsListening is returned when Listen() is called on an instance of webWorkers already listening
	ErrIsListening = errors.Error("cannot listen on an instance already listening")

	// ErrIsClosed is returned when an action is attempted on a closed instance
	ErrIsClosed = errors.Error("cannot perform action on closed instance")

	// ErrHeadersSent is returned when header modifications are attempted after the headers have already been sent
	ErrHeadersSent = errors.Error("headers already sent")

	// ErrEmptyCerts is returned when no certificates are available and the TLS setting is enabled
	ErrEmptyCerts = errors.Error("number of certificates must be greater than zero if TLS is enabled")

	// ErrEmptyAddress is returned when an empty address is provided
	ErrEmptyAddress = errors.Error("address cannot be empty")

	// ErrInvalidHeaderStatus is returned when an invalid header status is provided
	ErrInvalidHeaderStatus = errors.Error("invalid header status")

	// ErrInvalidStatusCode is returned when an invalid status code is provided
	ErrInvalidStatusCode = errors.Error("invalid status code")
)
View Source
const (
	// ContentTypeHTML is the html content type
	ContentTypeHTML = "text/html"
	// ContentTypeJS is the javascript content type
	ContentTypeJS = "application/js"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Cookie struct {
	Key  string
	Val  string
	Path string
	Exp  int64
}

Cookie represents a cookie

func (*Cookie) String

func (c *Cookie) String() string

type Cookies

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

Cookies represents of a set of cookies

func (*Cookies) Bytes

func (c *Cookies) Bytes() (bs []byte)

Bytes will return a byteslice representation of our Cookies

func (*Cookies) Dup

func (c *Cookies) Dup() (nc *Cookies)

Dup will return a copy of the Cookies, so it can be used after the HTTP request/response process has completed

func (*Cookies) Get

func (c *Cookies) Get(key string) (val string)

Get will return the value of the cookie matching the provided key

func (*Cookies) Set

func (c *Cookies) Set(key, val, path string, expires int64)

Set will set the value of the cookie matching the provided key

func (*Cookies) String

func (c *Cookies) String() string

String will return a string representation of our Cookies

type Handler

type Handler func(*Response, *Request)

Handler is the func used for handling http requests

type Opts

type Opts struct {
	// Number of workers (Note: will maintain a running goroutine for each worker)
	WorkerCap int `ini:"workerCap"`
	// Length of requests queue (IE: Requests sitting in memory, rather than waiting on disk using epoll/kqueue)
	QueueLen int `ini:"queueLen"`
	// Address to be serving from
	// TODO: Consider changing this to port, and making it a uint16
	Address string `ini:"address"`

	// Whether or not TLS is enabled
	TLS bool `ini:"tls"`
	// List of TLS certifications (Only needed if TLS is set to true)
	Certs []TLSPair

	ErrorOutput io.Writer
}

Opts are the options used to configure an instance of web workers

func NewOpts

func NewOpts(src interface{}) (o Opts, err error)

NewOpts returns new options given a provided source Please see the go-ini/ini docu (https://godoc.org/github.com/go-ini/ini#Load) for more information on the source argument

type Request

type Request struct {
	Body    io.Reader
	Cookies *Cookies
	// contains filtered or unexported fields
}

Request is an HTTP request

func (*Request) Accept

func (r *Request) Accept() string

Accept will return the accept

func (*Request) AcceptEncoding

func (r *Request) AcceptEncoding() string

AcceptEncoding will return the accept encoding

func (*Request) AcceptLanguage

func (r *Request) AcceptLanguage() string

AcceptLanguage will return the accept language

func (*Request) Connection

func (r *Request) Connection() string

Connection will return the connection

func (*Request) ContentLength

func (r *Request) ContentLength() int

ContentLength will return the content length

func (*Request) ContentType

func (r *Request) ContentType() string

ContentType will return the content type

func (*Request) HTTPType

func (r *Request) HTTPType() string

HTTPType will return the http type

func (*Request) Host

func (r *Request) Host() string

Host will return the host

func (*Request) Method

func (r *Request) Method() string

Method will return the method

func (*Request) Path

func (r *Request) Path() string

Path will return the path

func (*Request) UserAgent

func (r *Request) UserAgent() string

UserAgent will return the user agent

type Response

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

Response is an http response

func (*Response) ContentType

func (r *Response) ContentType(ct string) (err error)

ContentType will set the content type

func (*Response) StatusCode

func (r *Response) StatusCode(sc int) (err error)

StatusCode will set the status code

func (*Response) Write

func (r *Response) Write(b []byte) (err error)

type TLSPair

type TLSPair struct {
	CRT string
	Key string
}

TLSPair is a crt/key pair for TLS

type Webworkers

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

Webworkers is the manager the web workers service

func New

func New(o Opts, fn Handler) (ww *Webworkers, err error)

New returns a new instance of Webworkers

func (*Webworkers) Close

func (ww *Webworkers) Close() (err error)

Close will close an instance of web workers

func (*Webworkers) Listen

func (ww *Webworkers) Listen() (err error)

Listen will begin the listening loop

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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