go_webserver

package module
v1.3.3 Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2024 License: Apache-2.0 Imports: 18 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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"
	"github.com/randlabs/go-webserver/middleware"
	"github.com/randlabs/go-webserver/request"
)

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 *request.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
	DefaultMaxRequestsPerConn = 8
	DefaultMaxRequestBodySize = 4 * 1048576 // 4MB
)

Variables

This section is empty.

Functions

This section is empty.

Types

type HandlerFunc added in v1.1.1

type HandlerFunc func(req *request.RequestContext) error

HandlerFunc defines a function that handles a request.

func HandlerFromHttpHandler

func HandlerFromHttpHandler(handler http.Handler) HandlerFunc

HandlerFromHttpHandler returns a HandlerFunc based on the provided http.Handler

func HandlerFromHttpHandlerFunc

func HandlerFromHttpHandlerFunc(f http.HandlerFunc) HandlerFunc

HandlerFromHttpHandlerFunc 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 MiddlewareFunc added in v1.1.1

type MiddlewareFunc func(next HandlerFunc) HandlerFunc

MiddlewareFunc defines a function that is executed when a request is received.

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 number of concurrent client connections allowed per IP.
	MaxConnsPerIP int

	// Maximum number of requests served per connection.
	MaxRequestsPerConn int

	// Maximum request body size.
	MaxRequestBodySize int

	// Enable compression.
	EnableCompression 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
}

Options specifies the server creation options.

type RequestErrorHandler

type RequestErrorHandler func(req *request.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(options Options) (*Server, error)

Create creates a new webserver

func (*Server) CustomMethod added in v1.3.0

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

CustomMethod adds a custom method handler for the specified route

func (*Server) DELETE

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

DELETE adds a DELETE handler for the specified route

func (*Server) GET

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

GET adds a GET handler for the specified route

func (*Server) HEAD

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

HEAD adds a HEAD handler for the specified route

func (*Server) OPTIONS

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

OPTIONS adds a OPTIONS handler for the specified route

func (*Server) PATCH

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

PATCH adds a PATCH handler for the specified route

func (*Server) POST

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

POST adds a POST handler for the specified route

func (*Server) PUT

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

PUT adds a PUT handler for the specified route

func (*Server) ServeDebugProfiles added in v1.1.4

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

ServeDebugProfiles adds the GO runtime profile handlers to a web server

func (*Server) ServeFiles

func (srv *Server) ServeFiles(path string, opts ServerFilesOptions, middlewares ...MiddlewareFunc) 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 MiddlewareFunc)

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
}

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
⌂ 换网址