tcp

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2019 License: MIT Imports: 13 Imported by: 0

README

TCP

GoDoc Build Status Code Coverage Go Report Card

TCP provides interfaces to create a TCP server.

Installation

To install it, you need to install Go and set your Go workspace first. Download and install it:

$ go get -u github.com/rvflash/tcp

Import it in your code:

import "github.com/rvflash/tcp"
Prerequisite

tcp uses the Go modules that required Go 1.11 or later.

Quick start

Assuming the following code that runs a server on port 9090:

package main

import (
	"log"
	
	"github.com/rvflash/tcp"
)

func main() {
	// creates a server with a logger and a recover on panic as middlewares.
	r := tcp.Default()
	r.ACK(func(c *tcp.Context) {
		// new message received
		// gets the request body
		buf, err := c.ReadAll()
        if err != nil {
            c.Error(err)
        }
		// writes something as response
		c.String(string(buf))
	})
	err := r.Run(":9090") // listen and serve on 0.0.0.0:9090
	if err != nil {
		log.Fatalf("listen: %s", err)
	}
}

Documentation

Overview

Package tcp provides interfaces to create a TCP server.

Index

Examples

Constants

View Source
const (
	// LogRemoteAddr is the name of the log's field for the remote address.
	LogRemoteAddr = "addr"
	// LogRequestSize is the name of the log's field for the request size.
	LogRequestSize = "req_size"
	// LogResponseSize is the name of the log's field for the response size.
	LogResponseSize = "resp_size"
	// LogLatency is the name of the log's field with the response duration.
	LogLatency = "latency"
	// LogServerHostname is the name of the log's field with the server hostname.
	LogServerHostname = "server"
)
View Source
const (
	ANY = ""
	ACK = "ACK"
	FIN = "FIN"
	SYN = "SYN"
)

List of supported segments.

Variables

View Source
var ErrRequest = NewError("invalid request")

ErrRequest is returned if the request is invalid.

Functions

This section is empty.

Types

type Context

type Context struct {
	// Request contains information about the TCP request.
	Request *Request
	// ResponseWriter writes the response on the connection.
	ResponseWriter
	// Keys is a key/value pair allows data sharing inside the context of each request.
	Shared M
	// contains filtered or unexported fields
}

Context allows us to pass variables between middleware and manage the flow.

func (*Context) Abort

func (c *Context) Abort()

Abort prevents pending handlers from being called, but not interrupt the current handler.

func (*Context) Canceled

func (c *Context) Canceled() <-chan struct{}

Canceled is a shortcut to listen the request's cancellation.

func (*Context) Close

func (c *Context) Close() error

Close immediately closes the connection. An error is returned when we fail to do it.

func (*Context) Err

func (c *Context) Err() Errors

Err explains what failed during the request. The method name is inspired by the context package.

func (*Context) Error

func (c *Context) Error(err error)

Error reports a new error.

func (*Context) Get

func (c *Context) Get(key string) (value interface{}, exists bool)

Get retrieves in shared memory the given key.ResponseWriter It returns its value or not exists if it fails to found it..

func (*Context) GetBool

func (c *Context) GetBool(key string) (value bool)

GetBool returns the value associated with the key as a boolean.

func (*Context) GetDuration

func (c *Context) GetDuration(key string) (value time.Duration)

GetDuration returns the value associated with the key as a time duration.

func (*Context) GetFloat64

func (c *Context) GetFloat64(key string) (value float64)

GetFloat64 returns the value associated with the key as a float64.

func (*Context) GetInt

func (c *Context) GetInt(key string) (value int)

GetInt returns the value associated with the key as a int.

func (*Context) GetInt64

func (c *Context) GetInt64(key string) (value int64)

GetInt64 returns the value associated with the key as a int64.

func (*Context) GetString

func (c *Context) GetString(key string) (value string)

GetString returns the value associated with the key as a string.

func (*Context) Next

func (c *Context) Next()

Next should be used only inside middleware. It executes the pending handlers in the chain inside the calling handler.

func (*Context) ReadAll

func (c *Context) ReadAll() ([]byte, error)

ReadAll return the stream data.

func (*Context) String

func (c *Context) String(s string)

String writes the given string on the current connection.

func (*Context) Write

func (c *Context) Write(d []byte) (int, error)

Write implements the Conn interface.

type Err

type Err interface {
	error
	// Recovered returns true if the error comes from a panic recovering.
	Recovered() bool
}

Err represents a TCP error.

type Error

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

Error represents a error message. It can wraps another error, its cause.

func NewError

func NewError(msg string, cause ...error) *Error

NewError returns a new Error based of the given cause.

func (*Error) Error

func (e *Error) Error() string

Error implements the Err interface.

func (*Error) Recovered

func (e *Error) Recovered() bool

Recovered implements the Err interface.

type Errors

type Errors []error

Errors contains the list of errors occurred during the request.

func (Errors) Error

func (e Errors) Error() string

Error implements the Err interface.

func (Errors) Recovered

func (e Errors) Recovered() (ok bool)

Recovered implements the Err interface.

type Handler

type Handler interface {
	ServeTCP(ResponseWriter, *Request)
}

Handler responds to a TCP request.

type HandlerFunc

type HandlerFunc func(c *Context)

HandlerFunc defines the handler interface used as return value.

func Logger

func Logger(log *logrus.Logger, fields logrus.Fields) HandlerFunc

Logger returns a middleware to log each TCP request.

func Recovery

func Recovery() HandlerFunc

Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.

type M

type M map[string]interface{}

M is a shortcut for map[string]interface{}

type Request

type Request struct {
	// Segment specifies the TCP segment (SYN, ACK, FIN).
	Segment string
	// Body is the request's body.
	Body io.ReadCloser
	// LogRemoteAddr returns the remote network address.
	RemoteAddr string
	// contains filtered or unexported fields
}

Request represents an TCP request.

func NewRequest

func NewRequest(segment string, body io.Reader) *Request

NewRequest returns a new instance of request. A segment is mandatory as input. If empty, a SYN segment is used.

func (*Request) Cancel

func (r *Request) Cancel()

Cancel closes the request.

func (*Request) Canceled

func (r *Request) Canceled() <-chan struct{}

Canceled listens the context of the request until its closing.

func (*Request) Context

func (r *Request) Context() context.Context

Context returns the request's context.

func (*Request) WithCancel

func (r *Request) WithCancel(ctx context.Context) *Request

WithCancel returns a shallow copy of the given request with its context changed to ctx.

type ResponseRecorder

type ResponseRecorder struct {
	// Body is the buffer to which the Handler's Write calls are sent.
	Body *bytes.Buffer
}

ResponseRecorder is an implementation of http.ResponseWriter that records its changes.

func NewRecorder

func NewRecorder() *ResponseRecorder

NewRecorder returns an initialized writer to record the response.

func (*ResponseRecorder) Close

func (r *ResponseRecorder) Close() error

Close implements the ResponseWriter interface.

func (*ResponseRecorder) Size

func (r *ResponseRecorder) Size() int

Size implements the ResponseWriter interface.

func (*ResponseRecorder) Write

func (r *ResponseRecorder) Write(p []byte) (n int, err error)

Write implements the ResponseWriter interface.

func (*ResponseRecorder) WriteString

func (r *ResponseRecorder) WriteString(s string) (n int, err error)

WriteString allows to directly write string.

type ResponseWriter

type ResponseWriter interface {
	// Size returns the number of bytes already written into the response body.
	// -1: not already written
	Size() int
	io.WriteCloser
}

ResponseWriter interface is used by a TCP handler to write the response.

type Router

type Router interface {
	// Any registers a route that matches one of supported segment
	Any(segment string, handler ...HandlerFunc) Router
	// Use adds middleware fo any context: start and end of connection and message.
	Use(handler ...HandlerFunc) Router
	// ACK is a shortcut for Any("ACK", ...HandlerFunc).
	ACK(handler ...HandlerFunc) Router
	// FIN is a shortcut for Any("FIN", ...HandlerFunc).
	FIN(handler ...HandlerFunc) Router
	// SYN is a shortcut for Any("SYN", ...HandlerFunc).
	SYN(handler ...HandlerFunc) Router
}

Router is implemented by the Server.

type Server

type Server struct {
	// ReadTimeout is the maximum duration for reading the entire request, including the body.
	// A zero value for t means Read will not time out.
	ReadTimeout time.Duration
	// contains filtered or unexported fields
}

Server is the TCP server. It contains

func Default

func Default() *Server

Default returns an instance of TCP server with a Logger and a Recover on panic attached.

func New

func New() *Server

New returns a new instance of a TCP server.

Example
srv := tcp.New()
srv.SYN(sleep)
// now runs it!

func (*Server) ACK

func (s *Server) ACK(f ...HandlerFunc) Router

ACK allows to handle each new message.

func (*Server) Any

func (s *Server) Any(segment string, f ...HandlerFunc) Router

Any attaches handlers on the given segment.

func (*Server) FIN

func (s *Server) FIN(f ...HandlerFunc) Router

FIN allows to handle when the connection is closed.

func (*Server) Run

func (s *Server) Run(addr string) (err error)

Run starts listening on TCP address. This method will block the calling goroutine indefinitely unless an error happens.

func (*Server) SYN

func (s *Server) SYN(f ...HandlerFunc) Router

SYN allows to handle each new connection.

func (*Server) ServeTCP

func (s *Server) ServeTCP(w ResponseWriter, req *Request)

ServeTCP implements the Handler interface;

func (*Server) Use

func (s *Server) Use(f ...HandlerFunc) Router

Use adds middleware(s) on all segments.

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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