netpoll

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2021 License: MIT Imports: 11 Imported by: 5

README

netpoll

PkgGoDev Build Status codecov Go Report Card LICENSE

Package netpoll implements a network poller based on epoll/kqueue.

Features

  • Epoll/kqueue
  • TCP/UNIX
  • Compatible with the net.Conn interface.
  • Upgrade connection
  • Non-blocking I/O
  • Splice/sendfile
  • Rescheduling workers

Comparison to other packages.

Package net netpoll gnet evio
Low memory usage No Yes Yes Yes
Non-blocking I/O No Yes Yes Yes
Splice/sendfile Yes Yes No No
Rescheduling Yes Yes No No
Compatible with the net.Conn interface Yes Yes No No

Benchmark

mock 0msmock 1ms

Get started

Install
go get github.com/hslam/netpoll
Import
import "github.com/hslam/netpoll"
Usage
Simple Example
package main

import "github.com/hslam/netpoll"

func main() {
	var handler = &netpoll.DataHandler{
		NoShared:   true,
		NoCopy:     true,
		BufferSize: 1024,
		HandlerFunc: func(req []byte) (res []byte) {
			res = req
			return
		},
	}
	if err := netpoll.ListenAndServe("tcp", ":9999", handler); err != nil {
		panic(err)
	}
}
TLS Example
package main

import (
	"crypto/tls"
	"github.com/hslam/netpoll"
	"github.com/hslam/socket"
	"net"
)

func main() {
	var handler = &netpoll.DataHandler{
		NoShared:   true,
		NoCopy:     true,
		BufferSize: 1024,
		HandlerFunc: func(req []byte) (res []byte) {
			res = req
			return
		},
	}
	handler.SetUpgrade(func(conn net.Conn) (net.Conn, error) {
		tlsConn := tls.Server(conn, socket.DefalutTLSConfig())
		if err := tlsConn.Handshake(); err != nil {
			return nil, err
		}
		return tlsConn, nil
	})
	if err := netpoll.ListenAndServe("tcp", ":9999", handler); err != nil {
		panic(err)
	}
}
Websocket Example
package main

import (
	"github.com/hslam/netpoll"
	"github.com/hslam/websocket"
	"net"
)

func main() {
	var handler = &netpoll.ConnHandler{}
	handler.SetUpgrade(func(conn net.Conn) (netpoll.Context, error) {
		return websocket.Upgrade(conn, nil)
	})
	handler.SetServe(func(context netpoll.Context) error {
		ws := context.(*websocket.Conn)
		msg, err := ws.ReadMessage()
		if err != nil {
			return err
		}
		return ws.WriteMessage(msg)
	})
	if err := netpoll.ListenAndServe("tcp", ":9999", handler); err != nil {
		panic(err)
	}
}
HTTP Example
package main

import (
	"bufio"
	"github.com/hslam/mux"
	"github.com/hslam/netpoll"
	"github.com/hslam/response"
	"net"
	"net/http"
	"sync"
)

func main() {
	m := mux.New()
	m.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello World"))
	})
	ListenAndServe(":8080", m)
}

func ListenAndServe(addr string, handler http.Handler) error {
	var h = &netpoll.ConnHandler{}
	type Context struct {
		reader  *bufio.Reader
		rw      *bufio.ReadWriter
		conn    net.Conn
		serving sync.Mutex
	}
	h.SetUpgrade(func(conn net.Conn) (netpoll.Context, error) {
		reader := bufio.NewReader(conn)
		rw := bufio.NewReadWriter(reader, bufio.NewWriter(conn))
		return &Context{reader: reader, conn: conn, rw: rw}, nil
	})
	h.SetServe(func(context netpoll.Context) error {
		ctx := context.(*Context)
		ctx.serving.Lock()
		req, err := http.ReadRequest(ctx.reader)
		if err != nil {
			ctx.serving.Unlock()
			return err
		}
		res := response.NewResponse(req, ctx.conn, ctx.rw)
		handler.ServeHTTP(res, req)
		res.FinishRequest()
		ctx.serving.Unlock()
		response.FreeResponse(res)
		return nil
	})
	return netpoll.ListenAndServe("tcp", addr, h)
}
License

This package is licensed under a MIT license (Copyright (c) 2020 Meng Huang)

Author

netpoll was written by Meng Huang.

Documentation

Overview

Package netpoll implements a network poller based on epoll/kqueue.

Index

Constants

This section is empty.

Variables

View Source
var EAGAIN = syscall.EAGAIN

EAGAIN is the error when resource temporarily unavailable

View Source
var EOF = io.EOF

EOF is the error returned by Read when no more input is available.

View Source
var ErrHandler = errors.New("Handler must be not nil")

ErrHandler is the error when the Handler is nil

View Source
var ErrHandlerFunc = errors.New("HandlerFunc must be not nil")

ErrHandlerFunc is the error when the HandlerFunc is nil

View Source
var ErrListener = errors.New("Listener must be not nil")

ErrListener is the error when the Listener is nil

View Source
var ErrServeFunc = errors.New("Serve function must be not nil")

ErrServeFunc is the error when the Serve func is nil

View Source
var ErrServerClosed = errors.New("Server closed")

ErrServerClosed is returned by the Server's Serve and ListenAndServe methods after a call to Close.

View Source
var ErrTimeout = errors.New("non-positive interval for SetTimeout")

ErrTimeout is the error returned by SetTimeout when time.Duration d < time.Millisecond.

View Source
var ErrUpgradeFunc = errors.New("Upgrade function must be not nil")

ErrUpgradeFunc is the error when the Upgrade func is nil

View Source
var Tag = "epoll"

Tag is the poll type.

Functions

func ListenAndServe

func ListenAndServe(network, address string, handler Handler) error

ListenAndServe listens on the network address and then calls Serve with handler to handle requests on incoming connections.

The handler must be not nil.

ListenAndServe always returns a non-nil error.

func Serve

func Serve(lis net.Listener, handler Handler) error

Serve accepts incoming connections on the listener l, and registers the conn fd to poll. The poll will trigger the fd to read requests and then call handler to reply to them.

The handler must be not nil.

Serve always returns a non-nil error.

Types

type ConnHandler

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

ConnHandler implements the Handler interface.

func (*ConnHandler) Serve

func (h *ConnHandler) Serve(ctx Context) error

Serve implements the Handler Serve method.

func (*ConnHandler) SetServe

func (h *ConnHandler) SetServe(serve func(Context) error) *ConnHandler

SetServe sets the Serve function for once serving.

func (*ConnHandler) SetUpgrade

func (h *ConnHandler) SetUpgrade(upgrade func(net.Conn) (Context, error)) *ConnHandler

SetUpgrade sets the Upgrade function for upgrading the net.Conn.

func (*ConnHandler) Upgrade

func (h *ConnHandler) Upgrade(conn net.Conn) (Context, error)

Upgrade implements the Handler Upgrade method.

type Context

type Context interface{}

Context is returned by Upgrade for serving.

type DataHandler

type DataHandler struct {
	// NoShared disables the DataHandler to use the buffer pool for high performance.
	// Default NoShared is false to use the buffer pool for low memory usage.
	NoShared bool
	// NoCopy returns the bytes underlying buffer when NoCopy is true,
	// The bytes returned is shared by all invocations of Read, so do not modify it.
	// Default NoCopy is false to make a copy of data for every invocations of Read.
	NoCopy bool
	// BufferSize represents the buffer size.
	BufferSize int

	// HandlerFunc is the data Serve function.
	HandlerFunc func(req []byte) (res []byte)
	// contains filtered or unexported fields
}

DataHandler implements the Handler interface.

func (*DataHandler) Serve

func (h *DataHandler) Serve(ctx Context) error

Serve should serve a single request with the Context ctx.

func (*DataHandler) SetUpgrade

func (h *DataHandler) SetUpgrade(upgrade func(net.Conn) (net.Conn, error))

SetUpgrade sets the Upgrade function for upgrading the net.Conn.

func (*DataHandler) Upgrade

func (h *DataHandler) Upgrade(conn net.Conn) (Context, error)

Upgrade sets the net.Conn to a Context.

type Event

type Event struct {
	// Fd is a file descriptor.
	Fd int
	// Mode represents the event mode.
	Mode Mode
}

Event represents the poll event for the poller.

type Handler

type Handler interface {
	// Upgrade upgrades the net.Conn to a Context.
	Upgrade(net.Conn) (Context, error)
	// Serve should serve a single request with the Context.
	Serve(Context) error
}

Handler responds to a single request.

func NewHandler

func NewHandler(upgrade func(net.Conn) (Context, error), serve func(Context) error) Handler

NewHandler returns a new Handler.

type Mode

type Mode int

Mode represents the read/write mode.

const (
	// READ is the read mode.
	READ Mode = 1 << iota
	// WRITE is the write mode.
	WRITE
)

type Poll

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

Poll represents the poll that supports non-blocking I/O on file descriptors with polling.

func Create

func Create() (*Poll, error)

Create creates a new poll.

func (*Poll) Close

func (p *Poll) Close() error

Close closes the poll fd. The underlying file descriptor is closed by the destroy method when there are no remaining references.

func (*Poll) Register

func (p *Poll) Register(fd int) (err error)

Register registers a file descriptor.

func (*Poll) SetTimeout

func (p *Poll) SetTimeout(d time.Duration) (err error)

SetTimeout sets the wait timeout.

func (*Poll) Unregister

func (p *Poll) Unregister(fd int) (err error)

Unregister unregisters a file descriptor.

func (*Poll) Wait

func (p *Poll) Wait(events []Event) (n int, err error)

Wait waits events.

func (*Poll) Write

func (p *Poll) Write(fd int) (err error)

Write adds a write event.

type Server

type Server struct {
	Network string
	Address string
	// Handler responds to a single request.
	Handler Handler
	// NoAsync disables async.
	NoAsync         bool
	UnsharedWorkers int
	SharedWorkers   int
	TasksPerWorker  int
	// contains filtered or unexported fields
}

Server defines parameters for running a server.

func (*Server) Close

func (s *Server) Close() error

Close closes the server.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe listens on the network address and then calls Serve with handler to handle requests on incoming connections.

ListenAndServe always returns a non-nil error. After Close the returned error is ErrServerClosed.

func (*Server) Serve

func (s *Server) Serve(l net.Listener) (err error)

Serve accepts incoming connections on the listener l, and registers the conn fd to poll. The poll will trigger the fd to read requests and then call handler to reply to them.

The handler must be not nil.

Serve always returns a non-nil error. After Close the returned error is ErrServerClosed.

Jump to

Keyboard shortcuts

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