wenex

package module
v1.8.1 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2023 License: MIT Imports: 16 Imported by: 0

README

wenex

GoDoc Go Report Card

Simple and fast web framework for Go

Table of Contents

Requirements

Go >= 1.17

Quick Start

Download and Install
go get -u github.com/nexcode/wenex
Simple Example
package main

import (
	"io"
	"net/http"

	"github.com/nexcode/wenex"
)

func first(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "Hello,")
	wenex.GetRun(r.Context()).Next()
	io.WriteString(w, "!")
}

func second(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, " World")
}

func main() {
	config := wenex.DefaultConfig()
	config["server.http.listen"] = ":8080"

	wnx, err := wenex.New("simpleapp", config, nil)
	if err != nil {
		panic(err)
	}

	if err = wnx.Router.StrictRoute("/", "HEAD", "GET").Chain(first, second); err != nil {
		panic(err)
	}

	wnx.Logger("info").Print("running application...")

	if err = wnx.Run(); err != nil {
		panic(err)
	}
}

Open your browser and visit http://localhost:8080

Starting the webserver

In its simplest form, a webserver can be started like this:

config := wenex.DefaultConfig()
config["server.http.listen"] = ":8080"

wnx, err := wenex.New("simpleapp", config)
if err != nil {
	panic(err)
}

// define routing and something else...

if err = wnx.Run(); err != nil {
	panic(err)
}

In this simple example:
server.http.listen - port that will listen to the webserver
simpleapp - name of the application (a simpleapp.conf file will be created in the working directory)
config - configuration options

Configuration options

  • server.gzip.enable - enables and disables gzip
  • server.gzip.level - gzip compression level
  • server.http.listen - port that will listen to http traffic
  • server.https.listen - port that will listen to TLS (https) traffic
  • server.https.stringCert.cert - string containing certificate
  • server.https.stringCert.key - string containing private key
  • server.https.loadCert.cert - file containing certificate
  • server.https.loadCert.key - file containing private key
  • server.https.autoCert.hosts - array of domains
  • server.https.autoCert.dirCache - cache directory
  • server.timeout.read - connection read timeout
  • server.timeout.write - connection write timeout
  • server.timeout.idle - connection idle timeout
  • logger.defaultName - log filename for empty logger
  • logger.namePrefix - prefix that will be added to all saved log files. For example, if you use log/ prefix, then all logs files will be in log/ folder
  • logger.useFlag - sets the output flags for the logger. The flag bits are Ldate, Ltime, and so on
  • logger.usePrefix - string that will be added at the beginning of each message

Work with config file

If you run wenex with this config:

config := wenex.DefaultConfig()

wnx, err := wenex.New("simpleapp", config)
if err != nil {
	panic(err)
}

// Some code and wnx.Run()

A config file (simpleapp.conf) appears in the working directory.
From the config variable, only missing values will be written to the file.
Overwriting existing values will not occur.

{
    "log": {
        "filePrefix": "log/"
    },
    "server": {
        "http": {
            "listen": ":http"
        },
        "timeout": {
            "idle": "30s",
            "read": "30s",
            "write": "30s"
        }
    }
}

You can add any parameters directly to the file or use api:

wnx.Config.Set("key1.key2.keyN", 1000)
err := wnx.Config.Save()

After this, the config file will look like this:

{
    "key1": {
        "key2": {
            "keyN": 1000
        }
    },
    "log": {
        "filePrefix": "log/"
    },
    "server": {
        "http": {
            "listen": ":http"
        },
        "timeout": {
            "idle": "30s",
            "read": "30s",
            "write": "30s"
        }
    }
}

You can get the value of the parameters by api:

valueF64, err := wnx.Config.Float64("key1.key2.keyN")
// Or use it (panic on type error):
// value := wnx.Config.MustFloat64("key1.key2.keyN")

valueStr, err := wnx.Config.String("server.http.listen")
// Or use it (panic on type error):
// value := wnx.Config.MustString("server.http.listen")

// You can get the value as an interface{}
valueInterface := wnx.Config.Get("key")

Routing configuration

For the routing declaration in wenex two methods are used:

  • wnx.Router.StrictRoute(pattern, methods) - tied to the end of pattern
  • wnx.Router.WeakRoute(pattern, methods) - not tied to the end of pattern

Wenex supports the following special constructs in the pattern:

  • * - a sequence of any characters, including the empty string
  • :name - value of this path element will be available as a value of a get-variable with the same name

Routing declaration returns a method, that allows you to specify multiple handlers:
wnx.Router.StrictRoute(pattern, methods).Chain(handler1, handler2, handlerN)

Matching examples:

wnx.Router.StrictRoute("/*/:var/test/", "HEAD", "GET").Chain(...)
// matching requests:
// /sefsef/aaa/test/
// /zzz/qwe/test/

wnx.Router.WeakRoute("/*/:var/test/", "HEAD", "GET").Chain(...)
// matching requests:
// /sefsef/aaa/test/
// /zzz/zxc/test/rrr/
// /zzz/gg/test/ppp/fff

Chains can run completely sequentially, or you can call the next chain before the first one has completed.
For this, the Next() method is used.
An example of this behavior is given in the section Simple Example.

Work with logger

Winx creates files with logs dynamically.
It use log.filePrefix fo path prefix fo all logs files.
For example:

wnx.Logger("file1").Print("some data...")
wnx.Logger("folder2/file2").Print("some data...")

// default log file:
wnx.Logger("").Print("some data...")

You can customize the logger in accordance with the std log.logger api:

wnx.Logger("").SetPrefix("prefix")

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrHandlerType = Handler must be «http.Handler» or «func(http.ResponseWriter, *http.Request)»
	ErrHandlerType = errors.New("Handler must be «http.Handler» or «func(http.ResponseWriter, *http.Request)»")

	// ErrConfigListenType = Configuration value «server.http(s).listen» must be a string type
	ErrConfigListenType = errors.New("Configuration value «server.http(s).listen» must be a string type")

	// ErrNoServers = No servers to run. Set «server.http(s).listen» in configuration file
	ErrNoServers = errors.New("No servers to run. Set «server.http(s).listen» in configuration file")

	// ErrDefaultLogEmpty = Configuration value «logger.defaultName» must be a non-empty string
	ErrDefaultLogEmpty = errors.New("Configuration value «logger.defaultName» must be a non-empty string")

	// ErrNeedTLSConfigForHTTPS = To create a https lisener, you need to specify the tls config options
	ErrNeedTLSConfigForHTTPS = errors.New("To create a https lisener, you need to specify the tls config options")
)

Functions

func DefaultConfig

func DefaultConfig() map[string]interface{}

DefaultConfig returns default configuration options:

server.http.listen:   ":http"
server.timeout.read:  "30s"
server.timeout.write: "30s"
server.timeout.idle:  "30s"
logger.defaultName:   "wenex"
logger.namePrefix:    "log/"
logger.usePrefix:     "[!] "
logger.useFlag:       log.LstdFlags

func NewLogger added in v1.2.1

func NewLogger(config *joneva.Joneva, logWriter LogWriter) (func(string) *log.Logger, error)

Types

type Chain

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

Chain struct

func (*Chain) Chain

func (c *Chain) Chain(handlers ...interface{}) error

Chain adds a http.Handler or func(http.ResponseWriter, *http.Request) to the chain. It will be called on http request when the current router is selected.

func (*Chain) MustChain added in v1.3.0

func (c *Chain) MustChain(handlers ...interface{})

MustChain same as Chain, but causes panic

type LogWriter added in v1.2.0

type LogWriter interface {
	GetWriter(string) (io.Writer, error)
}

LogWriter used to connect custom loggers to wenex

type Router

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

Router struct

func (*Router) StrictRoute

func (r *Router) StrictRoute(pattern string, methods ...string) *Chain

StrictRoute routing binds expression to the end of line

func (*Router) WeakRoute

func (r *Router) WeakRoute(pattern string, methods ...string) *Chain

WeakRoute routing don't binds expression to the end of line

type Run

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

Run struct

func GetRun

func GetRun(ctx context.Context) *Run

GetRun return wenex.Run from context for current handler. It used to manage current handlers chain.

func (*Run) Break

func (r *Run) Break()

Break method

func (*Run) Next

func (r *Run) Next() bool

Next method

type Wenex

type Wenex struct {
	Router *Router
	Logger func(string) *log.Logger
	Config *joneva.Joneva
	// contains filtered or unexported fields
}

Wenex struct

func New

func New(configFile string, defaultConfig map[string]interface{}, logWriter LogWriter, configOverride ...string) (*Wenex, error)

New return a new Wenex object:

configFile: sets default config filename
defaultConfig: contains default configuration parameters
logWriter: interface for piping all logs to writer
configOverride: overrides config values by values from specified files

defaultConfig doesn't replace parameters declared in configuration file and writes new values to configuration file.

func (*Wenex) Close added in v1.1.0

func (wnx *Wenex) Close() error

Close immediately closes all active net.Listeners and any connections in state StateNew, StateActive, or StateIdle. For a graceful shutdown, use Shutdown.

Close does not attempt to close (and does not even know about) any hijacked connections, such as WebSockets.

Close returns any error returned from closing the Server's underlying Listener(s).

func (*Wenex) ConnState

func (wnx *Wenex) ConnState(f func(net.Conn, http.ConnState))

ConnState specifies an optional callback function that is called when a client connection changes state. See the ConnState type and associated constants for details.

func (*Wenex) Run

func (wnx *Wenex) Run() error

Run starts the web server. If an error occurs during the operation, the error will be returned. This method goes to asleep.

func (*Wenex) Shutdown added in v1.1.0

func (wnx *Wenex) Shutdown(timeout time.Duration) error

Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down. If the provided context expires before the shutdown is complete, Shutdown returns the context's error, otherwise it returns any error returned from closing the Server's underlying Listener(s).

When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return ErrServerClosed. Make sure the program doesn't exit and waits instead for Shutdown to return.

Shutdown does not attempt to close nor wait for hijacked connections such as WebSockets. The caller of Shutdown should separately notify such long-lived connections of shutdown and wait for them to close, if desired. See RegisterOnShutdown for a way to register shutdown notification functions.

Once Shutdown has been called on a server, it may not be reused; future calls to methods such as Serve will return ErrServerClosed.

Jump to

Keyboard shortcuts

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