go_webserver

package module
v2.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2024 License: Apache-2.0 Imports: 25 Imported by: 0

README

go-webserver

HTTP web server library for Go based on FastHttp

Usage with example

package example

import (
	"fmt"
	"os"
	"os/signal"
	"syscall"

	webserver "github.com/randlabs/go-webserver/v2"
	"github.com/randlabs/go-webserver/v2/middleware"
)

type testApiOutput struct {
	Status  string `json:"status"`
}

func main() {
	// Options struct has all the documentation
	srvOpts := webserver.Options{
		Address: "127.0.0.1",
		Port:    3000,
	}
	srv, err := webserver.Create(srvOpts)
	if err != nil {
		fmt.Printf("unable to create web server [%v]\n", err)
		return
	}

	// Add some middlewares
	srv.Use(middleware.DefaultCORS())

	// Setup a route
	srv.GET("/test", getTestApi)

	// Start server
	err = srv.Start()
	if err != nil {
		fmt.Printf("unable to start web server [%v]\n", err)
		return
	}

	fmt.Println("Server running. Press CTRL+C to stop.")

	// Wait for CTRL+C
	c := make(chan os.Signal, 2)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	<-c
	fmt.Println("Shutting down...")

	// Stop web server
	srv.Stop()
}

func getTestApi(req *webserver.RequestContext) error {
	// Prepare output
	output := testApiOutput{
		Status: "all systems operational",
    }

	// Encode and send output
	req.WriteJSON(output)
	req.Success()
	return nil
}

License

See LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	DefaultReadTimeout        = 10 * time.Second
	DefaultWriteTimeout       = 10 * time.Second
	DefaultMaxRequestBodySize = 4 * 1048576 // 4MB
)

Variables

This section is empty.

Functions

This section is empty.

Types

type HandlerFunc

type HandlerFunc func(req *RequestContext) error

HandlerFunc defines a function that handles a request.

func NewHandlerFromHttpHandler

func NewHandlerFromHttpHandler(handler http.Handler) HandlerFunc

NewHandlerFromHttpHandler returns a HandlerFunc based on the provided http.Handler

func NewHandlerFromHttpHandlerFunc

func NewHandlerFromHttpHandlerFunc(f http.HandlerFunc) HandlerFunc

NewHandlerFromHttpHandlerFunc returns a HandlerFunc based on the provided http.HandlerFunc

type ListenErrorHandler

type ListenErrorHandler func(srv *Server, err error)

ListenErrorHandler is a callback to call if an error is encountered in the network listener.

type Options

type Options struct {
	// Server name to use when sending response headers. Defaults to 'go-webserver'.
	Name string

	// Address is the bind address to attach the server listener.
	Address string

	// Port is the port number the server will listen.
	Port uint16

	// ReadTimeout is the amount of time allowed to read the full request including body. The connection's read
	// deadline is reset when the connection opens, or for keep-alive connections after the first byte has been read.
	ReadTimeout time.Duration

	// WriteTimeout is the maximum duration before timing out writes of the response. It is reset after the
	// request handler has returned.
	WriteTimeout time.Duration

	// The maximum number of concurrent connections the server may serve. Defaults to 256K connections.
	Concurrency int

	// Maximum request body size.
	MaxRequestBodySize int

	// Closes incoming connections after sending the first response to client.
	DisableKeepalive bool

	// Enable request body streaming and call the handler sooner when given body is larger than the current limit.
	StreamRequestBody bool

	// Disable Multipart Form data parsing and return the binary blob instead.
	DisablePreParseMultipartForm bool

	// A callback to call if an error is encountered.
	ListenErrorHandler ListenErrorHandler

	// A callback to handle errors in requests.
	RequestErrorHandler RequestErrorHandler

	// A custom handler for 404 errors
	NotFoundHandler HandlerFunc

	// A custom handler for 405 errors
	MethodNotAllowedHandler HandlerFunc

	// TLSConfig optionally provides a TLS configuration for use.
	TLSConfig *tls.Config

	// If MinReqFileDescs is greater than zero, specifies the minimum number of required file descriptors
	// to be available.
	//
	// NOTES:
	// 1. Only valid on *nix operating systems.
	// 2. Starting from Go v1.19, the soft limit is automatically raised to the maximum allowed on process startup.
	MinReqFileDescs uint64

	// Use TrustedProxies to prevent header spoofing when you are behind a proxy. When used, and the remote IP
	// is a trusted proxy, the RequestContext object will behalf in the following way:
	//   1. Scheme:   The value from X-Forwarded-Proto, X-Forwarded-Protocol, X-Forwarded-Ssl or X-Url-Scheme header
	//                will be used.
	//   2. RemoteIP: The value on ProxyHeader header will be used.
	//   3. Host:     The value from X-Forwarded-Host header will be used.
	TrustedProxies []string
}

Options specifies the server creation options.

type RequestContext

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

func (*RequestContext) AccessDenied

func (req *RequestContext) AccessDenied(msg string)

func (*RequestContext) AddResponseHeader

func (req *RequestContext) AddResponseHeader(key string, value string)

func (*RequestContext) BadRequest

func (req *RequestContext) BadRequest(msg string)

func (*RequestContext) CallFastHttpHandler

func (req *RequestContext) CallFastHttpHandler(handler fasthttp.RequestHandler)

func (*RequestContext) Conn

func (req *RequestContext) Conn() (out1 net.Conn)

func (*RequestContext) ConnID

func (req *RequestContext) ConnID() (out1 uint64)

func (*RequestContext) ConnRequestNum

func (req *RequestContext) ConnRequestNum() (out1 uint64)

func (*RequestContext) ConnTime

func (req *RequestContext) ConnTime() (out1 time.Time)

func (*RequestContext) Deadline

func (req *RequestContext) Deadline() (out1 time.Time, out2 bool)

func (*RequestContext) Done

func (req *RequestContext) Done() (out1 <-chan struct{})

func (*RequestContext) Err

func (req *RequestContext) Err() (out1 error)

func (*RequestContext) Error

func (req *RequestContext) Error(msg string, statusCode int)

func (*RequestContext) FormFile

func (req *RequestContext) FormFile(in1 string) (out1 *multipart.FileHeader, out2 error)

func (*RequestContext) FormValue

func (req *RequestContext) FormValue(in1 string) (out1 []uint8)

func (*RequestContext) Hijack

func (req *RequestContext) Hijack(in1 fasthttp.HijackHandler)

func (*RequestContext) HijackSetNoResponse

func (req *RequestContext) HijackSetNoResponse(in1 bool)

func (*RequestContext) Hijacked

func (req *RequestContext) Hijacked() (out1 bool)

func (*RequestContext) Host

func (req *RequestContext) Host() string

func (*RequestContext) ID

func (req *RequestContext) ID() (out1 uint64)

func (*RequestContext) IfModifiedSince

func (req *RequestContext) IfModifiedSince(in1 time.Time) (out1 bool)

func (*RequestContext) Init

func (req *RequestContext) Init(in1 *fasthttp.Request, in2 net.Addr, in3 fasthttp.Logger)

func (*RequestContext) Init2

func (req *RequestContext) Init2(in1 net.Conn, in2 fasthttp.Logger, in3 bool)

func (*RequestContext) InternalServerError

func (req *RequestContext) InternalServerError(msg string)

func (*RequestContext) IsBodyStream

func (req *RequestContext) IsBodyStream() (out1 bool)

func (*RequestContext) IsConnect

func (req *RequestContext) IsConnect() (out1 bool)

func (*RequestContext) IsDelete

func (req *RequestContext) IsDelete() (out1 bool)

func (*RequestContext) IsGet

func (req *RequestContext) IsGet() (out1 bool)

func (*RequestContext) IsHead

func (req *RequestContext) IsHead() (out1 bool)

func (*RequestContext) IsOptions

func (req *RequestContext) IsOptions() (out1 bool)

func (*RequestContext) IsPatch

func (req *RequestContext) IsPatch() (out1 bool)

func (*RequestContext) IsPost

func (req *RequestContext) IsPost() (out1 bool)

func (*RequestContext) IsPut

func (req *RequestContext) IsPut() (out1 bool)

func (*RequestContext) IsTLS

func (req *RequestContext) IsTLS() (out1 bool)

func (*RequestContext) IsTrace

func (req *RequestContext) IsTrace() (out1 bool)

func (*RequestContext) LastTimeoutErrorResponse

func (req *RequestContext) LastTimeoutErrorResponse() (out1 *fasthttp.Response)

func (*RequestContext) LocalAddr

func (req *RequestContext) LocalAddr() (out1 net.Addr)

func (*RequestContext) LocalIP

func (req *RequestContext) LocalIP() (out1 net.IP)

func (*RequestContext) Logger

func (req *RequestContext) Logger() (out1 fasthttp.Logger)

func (*RequestContext) Method

func (req *RequestContext) Method() (out1 []uint8)

func (*RequestContext) MultipartForm

func (req *RequestContext) MultipartForm() (out1 *multipart.Form, out2 error)

func (*RequestContext) Next

func (req *RequestContext) Next() error

func (*RequestContext) NoContent

func (req *RequestContext) NoContent(statusCode int)

func (*RequestContext) NotFound

func (req *RequestContext) NotFound(msg string)

func (*RequestContext) Path

func (req *RequestContext) Path() (out1 []uint8)

func (*RequestContext) PostArgs

func (req *RequestContext) PostArgs() (out1 *fasthttp.Args)

func (*RequestContext) PostBody

func (req *RequestContext) PostBody() (out1 []uint8)

func (*RequestContext) QueryArgs

func (req *RequestContext) QueryArgs() (out1 *fasthttp.Args)

func (*RequestContext) Redirect

func (req *RequestContext) Redirect(in1 string, in2 int)

func (*RequestContext) RedirectBytes

func (req *RequestContext) RedirectBytes(in1 []uint8, in2 int)

func (*RequestContext) Referer

func (req *RequestContext) Referer() (out1 []uint8)

func (*RequestContext) RemoteAddr

func (req *RequestContext) RemoteAddr() (out1 net.Addr)

func (*RequestContext) RemoteIP

func (req *RequestContext) RemoteIP() net.IP

func (*RequestContext) RemoveUserValue

func (req *RequestContext) RemoveUserValue(in1 interface{})

func (*RequestContext) RemoveUserValueBytes

func (req *RequestContext) RemoveUserValueBytes(in1 []uint8)

func (*RequestContext) Request

func (req *RequestContext) Request() *fasthttp.Request

func (*RequestContext) RequestBodyStream

func (req *RequestContext) RequestBodyStream() (out1 io.Reader)

func (*RequestContext) RequestHeader

func (req *RequestContext) RequestHeader(key string) string

func (*RequestContext) RequestHeaders

func (req *RequestContext) RequestHeaders() *fasthttp.RequestHeader

func (*RequestContext) RequestURI

func (req *RequestContext) RequestURI() (out1 []uint8)

func (*RequestContext) ResetBody

func (req *RequestContext) ResetBody()

func (*RequestContext) ResetUserValues

func (req *RequestContext) ResetUserValues()

func (*RequestContext) Response

func (req *RequestContext) Response() *fasthttp.Response

func (*RequestContext) ResponseHeaders

func (req *RequestContext) ResponseHeaders() *fasthttp.ResponseHeader

func (*RequestContext) Scheme

func (req *RequestContext) Scheme() string

func (*RequestContext) SendFile

func (req *RequestContext) SendFile(in1 string)

func (*RequestContext) SendFileBytes

func (req *RequestContext) SendFileBytes(in1 []uint8)

func (*RequestContext) ServiceUnavailable

func (req *RequestContext) ServiceUnavailable(msg string)

func (*RequestContext) SetBody

func (req *RequestContext) SetBody(in1 []uint8)

func (*RequestContext) SetBodyStream

func (req *RequestContext) SetBodyStream(in1 io.Reader, in2 int)

func (*RequestContext) SetBodyStreamWriter

func (req *RequestContext) SetBodyStreamWriter(in1 fasthttp.StreamWriter)

func (*RequestContext) SetBodyString

func (req *RequestContext) SetBodyString(in1 string)

func (*RequestContext) SetConnectionClose

func (req *RequestContext) SetConnectionClose()

func (*RequestContext) SetContentType

func (req *RequestContext) SetContentType(in1 string)

func (*RequestContext) SetContentTypeBytes

func (req *RequestContext) SetContentTypeBytes(in1 []uint8)

func (*RequestContext) SetRemoteAddr

func (req *RequestContext) SetRemoteAddr(in1 net.Addr)

func (*RequestContext) SetResponseHeader

func (req *RequestContext) SetResponseHeader(key string, value string)

func (*RequestContext) SetStatusCode

func (req *RequestContext) SetStatusCode(in1 int)

func (*RequestContext) SetUserContext

func (req *RequestContext) SetUserContext(ctx context.Context)

SetUserContext sets a context implementation by user.

func (*RequestContext) SetUserValue

func (req *RequestContext) SetUserValue(in1 interface{}, in2 interface{})

func (*RequestContext) SetUserValueBytes

func (req *RequestContext) SetUserValueBytes(in1 []uint8, in2 interface{})

func (*RequestContext) String

func (req *RequestContext) String() (out1 string)

func (*RequestContext) Success

func (req *RequestContext) Success()

func (*RequestContext) SuccessString

func (req *RequestContext) SuccessString(in1 string, in2 string)

func (*RequestContext) TLSConnectionState

func (req *RequestContext) TLSConnectionState() (out1 *tls.ConnectionState)

func (*RequestContext) Time

func (req *RequestContext) Time() (out1 time.Time)

func (*RequestContext) TimeoutError

func (req *RequestContext) TimeoutError(in1 string)

func (*RequestContext) TimeoutErrorWithCode

func (req *RequestContext) TimeoutErrorWithCode(in1 string, in2 int)

func (*RequestContext) TimeoutErrorWithResponse

func (req *RequestContext) TimeoutErrorWithResponse(in1 *fasthttp.Response)

func (*RequestContext) TooManyRequests

func (req *RequestContext) TooManyRequests(msg string)

func (*RequestContext) URI

func (req *RequestContext) URI() (out1 *fasthttp.URI)

func (*RequestContext) Unauthorized

func (req *RequestContext) Unauthorized(msg string)

func (*RequestContext) UserAgent

func (req *RequestContext) UserAgent() (out1 []uint8)

func (*RequestContext) UserContext

func (req *RequestContext) UserContext() context.Context

UserContext returns a context.Context previously set by the user. Defaults to context.Background.

func (*RequestContext) UserValue

func (req *RequestContext) UserValue(in1 interface{}) (out1 interface{})

func (*RequestContext) UserValueAsString added in v2.0.1

func (req *RequestContext) UserValueAsString(key []byte) (string, bool)

func (*RequestContext) UserValueBytes

func (req *RequestContext) UserValueBytes(in1 []uint8) (out1 interface{})

func (*RequestContext) Value

func (req *RequestContext) Value(in1 interface{}) (out1 interface{})

func (*RequestContext) VisitUserValues

func (req *RequestContext) VisitUserValues(in1 func([]uint8, interface{}))

func (*RequestContext) VisitUserValuesAll

func (req *RequestContext) VisitUserValuesAll(in1 func(interface{}, interface{}))

func (*RequestContext) Write

func (req *RequestContext) Write(in1 []uint8) (out1 int, out2 error)

func (*RequestContext) WriteJSON

func (req *RequestContext) WriteJSON(obj interface{})

func (*RequestContext) WriteString

func (req *RequestContext) WriteString(in1 string) (out1 int, out2 error)

type RequestContextPool

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

type RequestErrorHandler

type RequestErrorHandler func(req *RequestContext, err error)

RequestErrorHandler is a callback to call if an error is encountered while processing a request.

type Server

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

Server is the main server object

func Create

func Create(opts Options) (*Server, error)

Create creates a new webserver

func (*Server) CustomMethod

func (srv *Server) CustomMethod(method string, path string, handler HandlerFunc, middlewares ...HandlerFunc)

CustomMethod adds a custom method handler for the specified route

func (*Server) DELETE

func (srv *Server) DELETE(path string, handler HandlerFunc, middlewares ...HandlerFunc)

DELETE adds a DELETE handler for the specified route

func (*Server) GET

func (srv *Server) GET(path string, handler HandlerFunc, middlewares ...HandlerFunc)

GET adds a GET handler for the specified route

func (*Server) HEAD

func (srv *Server) HEAD(path string, handler HandlerFunc, middlewares ...HandlerFunc)

HEAD adds a HEAD handler for the specified route

func (*Server) OPTIONS

func (srv *Server) OPTIONS(path string, handler HandlerFunc, middlewares ...HandlerFunc)

OPTIONS adds a OPTIONS handler for the specified route

func (*Server) PATCH

func (srv *Server) PATCH(path string, handler HandlerFunc, middlewares ...HandlerFunc)

PATCH adds a PATCH handler for the specified route

func (*Server) POST

func (srv *Server) POST(path string, handler HandlerFunc, middlewares ...HandlerFunc)

POST adds a POST handler for the specified route

func (*Server) PUT

func (srv *Server) PUT(path string, handler HandlerFunc, middlewares ...HandlerFunc)

PUT adds a PUT handler for the specified route

func (*Server) ServeDebugProfiles

func (srv *Server) ServeDebugProfiles(basePath string, middlewares ...HandlerFunc)

ServeDebugProfiles adds the GO runtime profile handlers to a web server

func (*Server) ServeFiles

func (srv *Server) ServeFiles(path string, opts ServerFilesOptions, middlewares ...HandlerFunc) error

ServeFiles adds custom filesystem handler for the specified route

func (*Server) Start

func (srv *Server) Start() error

Start initiates listening

func (*Server) Stop

func (srv *Server) Stop()

Stop shuts down the web server

func (*Server) Use

func (srv *Server) Use(middleware HandlerFunc)

Use adds a middleware that will be executed as part of the request handler

type ServerFilesOptions

type ServerFilesOptions struct {
	// Base directory where public files are located
	RootDirectory string

	// If a path with no file is requested (like '/'), by default the file server will attempt to locate
	// 'index.html' and 'index.htm' files and serve them if available.
	DisableDefaultIndexPages bool

	// Accept client byte range requests
	AcceptByteRange bool

	// Custom file not found handler. Defaults to the server NotFound handler.
	NotFoundHandler HandlerFunc

	// File-system to use. Defaults to the OS file-system.
	FS fs.FS
}

ServerFilesOptions sets the parameters to use in a ServeFiles call

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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