goweb

package module
v0.14.1 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2022 License: MIT Imports: 5 Imported by: 0

README

Goweb

Light weight web framework based on net/http.

Includes

  • routing
  • middleware
  • logging

Goweb aims to

  1. rely only on the standard library as much as possible
  2. be flexible
  3. perform well

Usage

See examples.

Basic
package main

import (
	"github.com/twharmon/goweb"
)

func main() {
    app := goweb.New()
    app.GET("/hello/{name}", hello)
    app.Run(":8080")
}

func hello(c *goweb.Context) goweb.Responder {
    return c.JSON(goweb.Map{
        "hello": c.Param("name"),
    })
}
Logging
package main

import (
	"github.com/twharmon/goweb"
)

func main() {
    app := goweb.New()
	app.RegisterLogger(newLogger(goweb.LogLevelInfo))
    app.GET("/hello/{name}", hello)
    app.Run(":8080")
}

func hello(c *goweb.Context) goweb.Responder {
    c.LogInfo("param name:", c.Param("name"))
    // logs "[INFO] /hello/Gopher param name: Gopher"
    return c.JSON(goweb.Map{
        "hello": c.Param("name"),
    })
}

type logger struct{
	level goweb.LogLevel
}

func newLogger(level goweb.LogLevel) goweb.Logger {
	return &logger{level: level}
}

func (l *logger) Log(c *goweb.Context, logLevel goweb.LogLevel, messages ...interface{}) {
	if l.level > logLevel {
		return
	}
	prefix := fmt.Sprintf("[%s] %s", logLevel, c.Request.URL.Path)
	messages = append([]interface{}{prefix}, messages...)
	log.Println(messages...)
}
Auto TLS
package main

import (
	"context"
	"errors"
	"log"
	"net/http"

	"github.com/twharmon/goweb"
	"golang.org/x/crypto/acme/autocert"
)

func main() {
	app := goweb.New()
	app.GET("/", func(c *goweb.Context) goweb.Responder {
		return c.JSON(goweb.Map{
			"hello": "world",
		})
	})
	serveTLS(app)
}

func serveTLS(app *goweb.Engine) {
	m := &autocert.Manager{
		Cache:  autocert.DirCache(".certs"),
		Prompt: autocert.AcceptTOS,
		HostPolicy: func(_ context.Context, host string) error {
			if host == "example.com" {
				return nil
			}
			return errors.New("host not configured")
		},
	}
	go http.ListenAndServe(":http", m.HTTPHandler(nil))
	s := &http.Server{
		Addr:      ":https",
		TLSConfig: m.TLSConfig(),
		Handler:   app,
	}
	log.Fatalln(s.ListenAndServeTLS("", ""))
}
Easily extendable

See serving files, template rendering, tls, and logging for examples.

Documentation

For full documentation see pkg.go.dev.

Benchmarks

BenchmarkGinPlaintext        	 	       780 ns/op	    1040 B/op	       9 allocs/op
BenchmarkEchoPlaintext       	 	       817 ns/op	    1024 B/op	      10 allocs/op
BenchmarkGowebPlaintext      	  	      1241 ns/op	    1456 B/op	      16 allocs/op
BenchmarkGorillaPlaintext    	  	      1916 ns/op	    2032 B/op	      19 allocs/op
BenchmarkMartiniPlaintext    	   	     14448 ns/op	    1779 B/op	      36 allocs/op

BenchmarkGowebJSON           	   	     60042 ns/op	   50798 B/op	      15 allocs/op
BenchmarkGorillaJSON         	   	     61086 ns/op	   51330 B/op	      18 allocs/op
BenchmarkEchoJSON            	   	     61115 ns/op	   50280 B/op	      10 allocs/op
BenchmarkGinJSON             	   	     68322 ns/op	  100116 B/op	      10 allocs/op
BenchmarkMartiniJSON         	   	     96365 ns/op	  144335 B/op	      38 allocs/op

BenchmarkGinPathParams       	  	      2464 ns/op	    1952 B/op	      27 allocs/op
BenchmarkEchoPathParams      	  	      2600 ns/op	    1968 B/op	      27 allocs/op
BenchmarkGowebPathParams     	  	      3591 ns/op	    2673 B/op	      35 allocs/op
BenchmarkGorillaPathParams   	  	      4220 ns/op	    3265 B/op	      36 allocs/op
BenchmarkMartiniPathParams   	   	     15211 ns/op	    2657 B/op	      45 allocs/op

Contribute

Create a pull request to contribute to Goweb.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Context

type Context struct {
	ResponseWriter http.ResponseWriter
	Request        *http.Request
	// contains filtered or unexported fields
}

Context provides helper methods to read the request, get and set values in a data store, and send a response to the client. A new Context is constructed for each request, and is dropped when the response is sent.

func (*Context) Empty added in v0.8.0

func (c *Context) Empty(statusCode int) *EmptyResponse

Empty returns a EmptyResponse.

func (*Context) Get

func (c *Context) Get(key string) interface{}

Get gets a value from the Context data store.

func (*Context) JSON

func (c *Context) JSON(statusCode int, value interface{}) *JSONResponse

JSON returns a JSONResponse.

func (*Context) LogAlert

func (c *Context) LogAlert(messages ...interface{})

LogAlert logs the given messages for the logger where ShouldLog(LogLevelAlert) method returns true.

func (*Context) LogCritical

func (c *Context) LogCritical(messages ...interface{})

LogCritical logs the given messages for the logger where ShouldLog(LogLevelCritical) method returns true.

func (*Context) LogDebug

func (c *Context) LogDebug(messages ...interface{})

LogDebug logs the given messages for the logger where ShouldLog(LogLevelDebug) method returns true.

func (*Context) LogEmergency

func (c *Context) LogEmergency(messages ...interface{})

LogEmergency logs the given messages for the logger where ShouldLog(LogLevelEmergency) method returns true.

func (*Context) LogError

func (c *Context) LogError(messages ...interface{})

LogError logs the given messages for the logger where ShouldLog(LogLevelError) method returns true.

func (*Context) LogInfo

func (c *Context) LogInfo(messages ...interface{})

LogInfo logs the given messages for the logger where ShouldLog(LogLevelInfo) method returns true.

func (*Context) LogNotice

func (c *Context) LogNotice(messages ...interface{})

LogNotice logs the given messages for the logger where ShouldLog(LogLevelNotice) method returns true.

func (*Context) LogWarning

func (c *Context) LogWarning(messages ...interface{})

LogWarning logs the given messages for the logger where ShouldLog(LogLevelWarning) method returns true.

func (*Context) Nil added in v0.13.0

func (c *Context) Nil() *NilResponse

Nil does not return any response.

func (*Context) Param

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

Param gets a path parameter by the given name. An Empty string is returned if a parameter by the given name doesn't exist.

func (*Context) ParseJSON

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

ParseJSON parses the request body into the given target.

func (*Context) Query

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

Query gets a query value by the given name. An empty string is returned if a value by the given name doesn't exist.

func (*Context) Redirect added in v0.10.6

func (c *Context) Redirect(statusCode int, url string) *RedirectResponse

Redirect redirects the request.

func (*Context) Set

func (c *Context) Set(key string, value interface{})

Set sets a value in the Context data store.

func (*Context) SetCookie

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

SetCookie adds a Set-Cookie header to response.

func (*Context) Text added in v0.7.0

func (c *Context) Text(statusCode int, text string) *TextResponse

Text returns a TextResponse.

type EmptyResponse added in v0.8.0

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

EmptyResponse implements Responder interface. It sends as response without a body.

func (*EmptyResponse) Respond added in v0.8.0

func (r *EmptyResponse) Respond()

Respond sends a JSON response.

type Engine

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

Engine contains routing and logging information for your app.

func New

func New() *Engine

New returns a new Engine.

func (*Engine) DELETE

func (e *Engine) DELETE(path string, handler Handler)

DELETE registers a route for method DELETE.

func (*Engine) GET

func (e *Engine) GET(path string, handler Handler)

GET registers a route for method GET.

func (*Engine) HEAD

func (e *Engine) HEAD(path string, handler Handler)

HEAD registers a route for method HEAD.

func (*Engine) Middleware added in v0.9.0

func (e *Engine) Middleware(middleware ...Handler) *Middleware

Middleware returns a new middleware chain.

func (*Engine) NotFound

func (e *Engine) NotFound(handler Handler)

NotFound registers a handler to be called if no route is matched.

func (*Engine) OPTIONS

func (e *Engine) OPTIONS(path string, handler Handler)

OPTIONS registers a route for method OPTIONS.

func (*Engine) PATCH

func (e *Engine) PATCH(path string, handler Handler)

PATCH registers a route for method PATCH.

func (*Engine) POST

func (e *Engine) POST(path string, handler Handler)

POST registers a route for method POST.

func (*Engine) PUT

func (e *Engine) PUT(path string, handler Handler)

PUT registers a route for method PUT.

func (*Engine) RegisterLogger added in v0.10.1

func (e *Engine) RegisterLogger(logger Logger)

RegisterLogger registers a logger.

func (*Engine) Resource added in v0.12.0

func (e *Engine) Resource(resourceName string, resource Resource)

Resource creates multiple REST handlers from given interface.

func (*Engine) Run

func (e *Engine) Run(port string) error

Run starts a server on the given port.

func (*Engine) ServeHTTP

func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface.

func (*Engine) Shutdown added in v0.8.0

func (e *Engine) Shutdown() error

Shutdown shuts down the server.

type Handler

type Handler func(*Context) Responder

Handler handles HTTP requests.

type JSONResponse

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

JSONResponse implements Responder interface.

func (*JSONResponse) Respond

func (r *JSONResponse) Respond()

Respond sends a JSON response.

type LogLevel

type LogLevel int

LogLevel as defined in the RFC 5424 specification.

const (
	// LogLevelDebug as defined in the RFC 5424 specification.
	LogLevelDebug LogLevel = 1

	// LogLevelInfo as defined in the RFC 5424 specification.
	LogLevelInfo LogLevel = 2

	// LogLevelNotice as defined in the RFC 5424 specification.
	LogLevelNotice LogLevel = 3

	// LogLevelWarning as defined in the RFC 5424 specification.
	LogLevelWarning LogLevel = 4

	// LogLevelError as defined in the RFC 5424 specification.
	LogLevelError LogLevel = 5

	// LogLevelCritical as defined in the RFC 5424 specification.
	LogLevelCritical LogLevel = 6

	// LogLevelAlert as defined in the RFC 5424 specification.
	LogLevelAlert LogLevel = 7

	// LogLevelEmergency as defined in the RFC 5424 specification.
	LogLevelEmergency LogLevel = 8
)

func (LogLevel) String

func (l LogLevel) String() string

type Logger

type Logger interface {
	Log(ctx *Context, level LogLevel, messages ...interface{})
}

Logger is an interface that implements Log(level int, message interface{}).

type Map

type Map map[string]interface{}

Map is an alias for map[string]interface{}.

type Middleware

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

Middleware contains a set of Handler functions that will be applied in the same order in which they were registered.

func (*Middleware) DELETE added in v0.9.0

func (m *Middleware) DELETE(path string, handler Handler)

DELETE registers a route for method DELETE.

func (*Middleware) GET added in v0.9.0

func (m *Middleware) GET(path string, handler Handler)

GET registers a route for method GET.

func (*Middleware) HEAD added in v0.9.0

func (m *Middleware) HEAD(path string, handler Handler)

HEAD registers a route for method HEAD.

func (*Middleware) Middleware added in v0.10.0

func (m *Middleware) Middleware(middleware ...Handler) *Middleware

Middleware returns a new middleware chain.

func (*Middleware) PATCH added in v0.9.0

func (m *Middleware) PATCH(path string, handler Handler)

PATCH registers a route for method PATCH.

func (*Middleware) POST added in v0.9.0

func (m *Middleware) POST(path string, handler Handler)

POST registers a route for method POST.

func (*Middleware) PUT added in v0.9.0

func (m *Middleware) PUT(path string, handler Handler)

PUT registers a route for method PUT.

func (*Middleware) Resource added in v0.12.1

func (m *Middleware) Resource(resourceName string, resource Resource)

Resource creates multiple REST handlers from given interface.

type NilResponse added in v0.13.0

type NilResponse struct {
}

NilResponse implements Responder interface. It does not send any response. Useful for handlers that upgrade to WebSockets.

func (*NilResponse) Respond added in v0.13.0

func (r *NilResponse) Respond()

Respond does not do anything.

type RedirectResponse added in v0.10.6

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

RedirectResponse implements Responder interface.

func (*RedirectResponse) Respond added in v0.10.6

func (r *RedirectResponse) Respond()

Respond sends a plain text response.

type Resource added in v0.12.0

type Resource interface {
	Index(c *Context) Responder
	Get(c *Context) Responder
	Put(c *Context) Responder
	Delete(c *Context) Responder
	Post(c *Context) Responder
	Identifier() string
}

Resource handles Index, Get, Put, Delete, and Post requests.

type Responder

type Responder interface {
	Respond()
}

Responder is the Responder interface that responds to HTTP requests.

type TextResponse added in v0.7.0

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

TextResponse implements Responder interface.

func (*TextResponse) Respond added in v0.7.0

func (r *TextResponse) Respond()

Respond sends a plain text response.

Directories

Path Synopsis
examples
tls

Jump to

Keyboard shortcuts

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