connector

package module
v0.0.0-...-e3c1db2 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2024 License: MIT Imports: 22 Imported by: 0

README

connector

Build Status | codecov | Go Report Card | GoDoc

A simple and fast tcp server and client that make their communication by method, headers and body with support for server manager and client manager.

If i miss something or you have something interesting, please be part of this project. Let me know! My contact is at the end.

With support for

  • Methods
  • Headers
  • Middlewares

With response status

Constant Value
StatusOk 0
StatusCreated 1
StatusAccepted 2
StatusNoContent 3
StatusFound 4
StatusBadRequest 5
StatusUnauthorized 6
StatusNotFound 7
StatusConflict 8
StatusInternalError 9
StatusBadGateway 10
StatusUnavailable 11
StatusTimeout 12
Go
go get github.com/joaosoft/connector

Usage

This examples are available in the project at connector/examples

Configuration
{
  "server": {
    "address": ":9001",
    "log": {
      "level": "error"
    }
  },
  "client": {
    "log": {
      "level": "error"
    }
  },
  "server_manager": {
    "services": {
      "service_one": {
        "address": ":9001"
      },
      "service_two": {
        "address": ":9002"
      }
    },
    "log": {
      "level": "error"
    }
  },
  "client_manager": {
    "services": {
      "service_one": {
        "address": ":9001"
      },
      "service_two": {
        "address": ":9002"
      }
    },
    "log": {
      "level": "error"
    }
  }
}
Usage of Server and Client
Server
func main() {
	// create a new server
	w, err := connector.NewServer()
	if err != nil {
		panic(err)
	}

	w.AddMiddlewares(MyMiddlewareOne(), MyMiddlewareTwo())

	w.AddMethods(
		connector.NewMethod("sayHello", HandlerSayHello),
	)

	// start the server
	if err := w.Start(); err != nil {
		panic(err)
	}
}

func MyMiddlewareOne() connector.MiddlewareFunc {
	return func(next connector.HandlerFunc) connector.HandlerFunc {
		return func(ctx *connector.Context) error {
			fmt.Println("HELLO I'M THE MIDDLEWARE ONE")
			return next(ctx)
		}
	}
}

func MyMiddlewareTwo() connector.MiddlewareFunc {
	return func(next connector.HandlerFunc) connector.HandlerFunc {
		return func(ctx *connector.Context) error {
			fmt.Println("HELLO I'M THE MIDDLEWARE TWO")
			return next(ctx)
		}
	}
}

func HandlerSayHello(ctx *connector.Context) error {
	fmt.Println("HELLO I'M THE HELLO HANDER FOR POST")

	data := struct {
		Name string `json:"name"`
		Age  int    `json:"age"`
	}{}

	json.Unmarshal(ctx.Request.Body, &data)
	fmt.Printf("DATA: %+v", data)

	ctx.Response.WithBody([]byte("{ \"welcome\": \"" + data.Name + "\" }"))

	return nil
}
Client
func main() {
	// create a new client
	c, err := connector.NewClient()
	if err != nil {
		panic(err)
	}

	request(c)
}

func request(c *connector.Client) {
	data := struct {
		Name string `json:"name"`
		Age  int    `json:"age"`
	}{
		Name: "joao",
		Age:  30,
	}

	bytes, _ := json.Marshal(data)

	response, err := c.Invoke("sayHello", "localhost:9001", nil, bytes)
	if err != nil {
		panic(err)
	}

	fmt.Printf("%+v\n", string(response.Body))
}

Usage of Server Manager and Client Manager
Server Manager
func main() {
	serverManager, err := connector.NewServerManager()

	// server 1
	server1, err := connector.NewServer()
	if err != nil {
		panic(err)
	}
	server1.AddMethod("sayHello", HandlerSayHello)

	// server 2
	server2, err := connector.NewServer()
	if err != nil {
		panic(err)
	}
	server2.AddMethod("sayGoodbye", HandlerSayGoodbye)

	// server manager
	serverManager.Register("service_one", server1)
	serverManager.Register("service_two", server2)

	serverManager.Start()
}

func HandlerSayHello(ctx *connector.Context) error {
	fmt.Println("HELLO I'M THE HELLO HANDER FOR POST")

	data := struct {
		Name string `json:"name"`
		Age  int    `json:"age"`
	}{}

	json.Unmarshal(ctx.Request.Body, &data)
	fmt.Printf("DATA: %+v", data)

	ctx.Response.WithBody([]byte("{ \"welcome\": \"" + data.Name + "\" }")).WithStatus(connector.StatusAccepted)

	return nil
}

func HandlerSayGoodbye(ctx *connector.Context) error {
	fmt.Println("HELLO I'M THE HELLO HANDER FOR POST")

	data := struct {
		Name string `json:"name"`
		Age  int    `json:"age"`
	}{}

	json.Unmarshal(ctx.Request.Body, &data)
	fmt.Printf("DATA: %+v", data)

	ctx.Response.WithBody([]byte("{ \"goodbye\": \"" + data.Name + "\" }")).WithStatus(connector.StatusAccepted)

	return nil
}
Client Manager
func main() {
	// client manager
	clientManager, err := connector.NewClientManager()
	if err != nil {
		panic(err)
	}

	data := struct {
		Name string `json:"name"`
		Age  int    `json:"age"`
	}{
		Name: "joao",
		Age:  30,
	}

	bytes, err := json.Marshal(data)
	if err != nil {
		panic(err)
	}

	// invoke service_one
	response, err := clientManager.Invoke("service_one", "sayHello", nil, bytes)
	if err != nil {
		panic(err)
	}
	fmt.Printf("service_one response: %+v\n", string(response.Body))

	// invoke service_two
	response, err = clientManager.Invoke("service_two", "sayGoodbye", nil, bytes)
	if err != nil {
		panic(err)
	}
	fmt.Printf("service_two response: %+v\n", string(response.Body))
}

Known issues

Follow me at

Facebook: https://www.facebook.com/joaosoft

LinkedIn: https://www.linkedin.com/in/jo%C3%A3o-ribeiro-b2775438/

If you have something to add, please let me know joaosoft@gmail.com

Documentation

Index

Constants

View Source
const (
	HeaderTimeFormat = time.RFC3339
	TimeFormat       = time.RFC3339
)
View Source
const (
	// Headers
	HeaderServer    = "Server"
	HeaderDate      = "Date"
	HeaderHost      = "Host"
	HeaderUserAgent = "User-Agent"
)

Variables

View Source
var (
	ErrorMethodNotFound        = errors.New("method not found")
	ErrorServiceNotFound       = errors.New("service not found")
	ErrorConfigurationNotFound = errors.New("configuration not found")
	ErrorServerDown            = errors.New("server is down")
)

Functions

func CopyDir

func CopyDir(src string, dst string) error

CopyDir copies a whole directory recursively

func CopyFile

func CopyFile(src, dst string) error

CopyFile copies a single file from src to dst

func Exists

func Exists(file string) bool

func GetEnv

func GetEnv() string

func GetFreePort

func GetFreePort() (int, error)

func GetFunctionName

func GetFunctionName(i interface{}) string

func GetMimeType

func GetMimeType(fileName string) (mimeType string)

func NewSimpleConfig

func NewSimpleConfig(file string, obj interface{}) error

func ReadFile

func ReadFile(file string, obj interface{}) ([]byte, error)

func ReadFileLines

func ReadFileLines(file string) ([]string, error)

func StatusText

func StatusText(code Status) string

func WriteFile

func WriteFile(file string, obj interface{}) error

Types

type AppClientConfig

type AppClientConfig struct {
	Client ClientConfig `json:"client"`
}

func NewClientConfig

func NewClientConfig() (*AppClientConfig, error)

type AppClientManagerConfig

type AppClientManagerConfig struct {
	ClientManager ClientManagerConfig `json:"client_manager"`
}

func NewClientManagerConfig

func NewClientManagerConfig() (*AppClientManagerConfig, error)

type AppServerConfig

type AppServerConfig struct {
	Server ServerConfig `json:"server"`
}

func NewServerConfig

func NewServerConfig() (*AppServerConfig, error)

type AppServerManagerConfig

type AppServerManagerConfig struct {
	ServerManager ServerManagerConfig `json:"server_manager"`
}

func NewServerManagerConfig

func NewServerManagerConfig() (*AppServerManagerConfig, error)

type Base

type Base struct {
	IP      string
	Address string
	Method  string
	Headers Headers

	Server *Server
	Client *Client
	// contains filtered or unexported fields
}

func (*Base) BindHeaders

func (r *Base) BindHeaders(obj interface{}) error

func (*Base) GetHeader

func (r *Base) GetHeader(name string) string

func (*Base) SetHeader

func (r *Base) SetHeader(name string, header []string)

type Client

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

func NewClient

func NewClient(options ...ClientOption) (*Client, error)

func (*Client) Invoke

func (c *Client) Invoke(method, address string, headers Headers, body ...[]byte) (*Response, error)

func (*Client) NewRequest

func (c *Client) NewRequest(method string, address string, headers ...Headers) *Request

func (*Client) NewResponse

func (c *Client) NewResponse(method string, address string, conn net.Conn) (*Response, error)

func (*Client) Reconfigure

func (c *Client) Reconfigure(options ...ClientOption)

Reconfigure ...

func (*Client) Send

func (c *Client) Send(request *Request) (*Response, error)

type ClientConfig

type ClientConfig struct {
	Log Log `json:"log"`
}

type ClientManager

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

func NewClientManager

func NewClientManager(options ...ClientManagerOption) (*ClientManager, error)

func (*ClientManager) Invoke

func (cm *ClientManager) Invoke(service, method string, headers Headers, body ...[]byte) (*Response, error)

func (*ClientManager) Reconfigure

func (c *ClientManager) Reconfigure(options ...ClientManagerOption)

Reconfigure ...

type ClientManagerConfig

type ClientManagerConfig struct {
	Servers map[string]*ClientService `json:"Servers"`
	Log     Log                       `json:"log"`
}

type ClientManagerOption

type ClientManagerOption func(ClientManager *ClientManager)

ClientManagerOption ...

func WithClientManagerConfiguration

func WithClientManagerConfiguration(config *ClientManagerConfig) ClientManagerOption

WithClientManagerConfiguration ...

func WithClientManagerLogLevel

func WithClientManagerLogLevel(level logger.Level) ClientManagerOption

WithClientManagerLogLevel ...

func WithClientManagerLogger

func WithClientManagerLogger(logger logger.ILogger) ClientManagerOption

WithClientManagerLogger ...

type ClientOption

type ClientOption func(client *Client)

ClientOption ...

func WithClientConfiguration

func WithClientConfiguration(config *ClientConfig) ClientOption

WithClientConfiguration ...

func WithClientLogLevel

func WithClientLogLevel(level logger.Level) ClientOption

WithClientLogLevel ...

func WithClientLogger

func WithClientLogger(logger logger.ILogger) ClientOption

WithClientLogger ...

type ClientService

type ClientService struct {
	Address string `json:"address"`
}

type Clients

type Clients map[string]*Client

type Context

type Context struct {
	StartTime time.Time
	Request   *Request
	Response  *Response
}

func NewContext

func NewContext(startTime time.Time, request *Request, response *Response) *Context

func (*Context) Redirect

func (ctx *Context) Redirect(host string) error

type ErrorHandler

type ErrorHandler func(ctx *Context, err error) error

type HandlerFunc

type HandlerFunc func(ctx *Context) error

type Headers

type Headers map[string][]string

type Log

type Log struct {
	Level string `json:"level"`
}

type Method

type Method struct {
	Name        string
	Method      string
	Handler     HandlerFunc
	Middlewares []MiddlewareFunc
}

func NewMethod

func NewMethod(method string, handler HandlerFunc, middleware ...MiddlewareFunc) *Method

type Methods

type Methods map[string]*Method

type MiddlewareFunc

type MiddlewareFunc func(HandlerFunc) HandlerFunc

type Request

type Request struct {
	Base
	Body   []byte
	Reader io.Reader
	Writer io.Writer
}

func (*Request) Send

func (r *Request) Send() (*Response, error)

func (*Request) WithBody

func (r *Request) WithBody(body []byte) *Request

type RequestHandler

type RequestHandler struct {
	Conn    net.Conn
	Handler HandlerFunc
}

type Response

type Response struct {
	Base
	Body   []byte
	Status Status
	Reader io.Reader
	Writer io.Writer
}

func (*Response) WithBody

func (r *Response) WithBody(body []byte) *Response

type Server

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

func NewServer

func NewServer(options ...ServerOption) (*Server, error)

func (*Server) AddMethod

func (w *Server) AddMethod(method string, handler HandlerFunc, middleware ...MiddlewareFunc)

func (*Server) AddMethods

func (w *Server) AddMethods(methods ...*Method) error

func (*Server) AddMiddlewares

func (w *Server) AddMiddlewares(middlewares ...MiddlewareFunc)

func (*Server) DefaultErrorHandler

func (w *Server) DefaultErrorHandler(ctx *Context, err error) error

func (*Server) GetMethod

func (w *Server) GetMethod(method string) (*Method, error)

func (*Server) Implement

func (w *Server) Implement(implementation interface{}, middleware ...MiddlewareFunc)

func (*Server) NewRequest

func (w *Server) NewRequest(conn net.Conn, server *Server) (*Request, error)

func (*Server) NewResponse

func (w *Server) NewResponse(request *Request) *Response

func (*Server) Reconfigure

func (w *Server) Reconfigure(options ...ServerOption)

Reconfigure ...

func (*Server) SetErrorHandler

func (w *Server) SetErrorHandler(handler ErrorHandler) error

func (*Server) Start

func (w *Server) Start(waitGroup ...*sync.WaitGroup) error

func (*Server) Started

func (w *Server) Started() bool

func (*Server) Stop

func (w *Server) Stop(waitGroup ...*sync.WaitGroup) error

type ServerConfig

type ServerConfig struct {
	Address string `json:"address"`
	Log     Log    `json:"log"`
}

type ServerManager

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

func NewServerManager

func NewServerManager(options ...ServerManagerOption) (*ServerManager, error)

func (*ServerManager) Reconfigure

func (w *ServerManager) Reconfigure(options ...ServerManagerOption)

Reconfigure ...

func (*ServerManager) Register

func (sm *ServerManager) Register(server *Server) *ServerManager

func (*ServerManager) Start

func (sm *ServerManager) Start(waitGroup ...*sync.WaitGroup) error

func (*ServerManager) Started

func (sm *ServerManager) Started() bool

func (*ServerManager) Stop

func (sm *ServerManager) Stop(waitGroup ...*sync.WaitGroup) error

type ServerManagerConfig

type ServerManagerConfig struct {
	Servers map[string]*ServerService `json:"Servers"`
	Log     Log                       `json:"log"`
}

type ServerManagerOption

type ServerManagerOption func(ServerManager *ServerManager)

ServerManagerOption ...

func WithServerManagerConfiguration

func WithServerManagerConfiguration(config *ServerManagerConfig) ServerManagerOption

WithServerManagerConfiguration ...

func WithServerManagerLogLevel

func WithServerManagerLogLevel(level logger.Level) ServerManagerOption

WithServerManagerLogLevel ...

func WithServerManagerLogger

func WithServerManagerLogger(logger logger.ILogger) ServerManagerOption

WithServerManagerLogger ...

type ServerOption

type ServerOption func(server *Server)

ServerOption ...

func WithServerAddress

func WithServerAddress(address string) ServerOption

WithServerAddress ...

func WithServerConfiguration

func WithServerConfiguration(config *ServerConfig) ServerOption

WithServerConfiguration ...

func WithServerLogLevel

func WithServerLogLevel(level logger.Level) ServerOption

WithServerLogLevel ...

func WithServerLogger

func WithServerLogger(logger logger.ILogger) ServerOption

WithServerLogger ...

func WithServerName

func WithServerName(name string) ServerOption

WithServerName ...

type ServerService

type ServerService struct {
	Address string `json:"address"`
}

type Servers

type Servers map[string]*Server

type Status

type Status int
const (
	StatusOk    Status = 0
	StatusError Status = 1
)

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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