gateway

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 4, 2021 License: MIT Imports: 10 Imported by: 0

README

Gateway

Gateway is an HTTP server written in Golang.

Quick Start

package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/LYZhelloworld/gateway"
)

func main() {
	s := gateway.Default()
	cfg := gateway.Config{}
	cfg.Add("/hello", http.MethodGet, "api.gateway.hello")
	s.UseConfig(cfg)
	s.Register("api.gateway.hello", func(context *gateway.Context) {
		context.Response = []byte("hello, world")
	})
	if err := s.RunWithShutdown(":8080", 5*time.Second); err != nil {
		fmt.Println(err)
	}
}

Endpoint and Service

An endpoint is the URL path of the HTTP request. For example: /hello.

A service is a handler with a group of identifiers separated by dots (.) as its name. For example: api.gateway.hello. Every endpoint points to a service name. A service with exact the same service name can handle the request.

However, a service that is "more generic" than the service name indicated by the endpoint is still capable of handling the service, only if there is no other services that is "more specific". For example: if there is api.gateway but no api.gateway.hello, it can still handle api.gateway.hello request.

A service with name * will handle all requests if no other service handler exists and matches the service name given.

Server

Server.Config maps endpoints to service names. The endpoint here is a struct of both the path and the method.

Server.Services is a collection of all services with their name.

Server.Run() starts a server without shutting down procedure.

Server.RunWithShutdown() starts a server with shutdown timeout and will shutdown the server gracefully.

Context

Context is the thing that the handler requires when the server is running.

Context.Request contains all the information of the request.

Context.StatusCode is the status code of the response. It can be changed in the handler.

Context.Response is a byte array which contains the response body.

Context.Header contains headers of the response.

Middleware

Middleware will be executed before/after a request. They share the same context during the request flow.

During the execution of a middleware, you can call Context.Next() to continue with the following middlewares. The function will return after all the following middlewares (including the main handler) have been executed.

You can call Context.Interrupt() at any time inside these middlewares. After the middleware returns, the following middlewares will not be executed, but the response will still be written.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config map[Endpoint]string

Config is a map that matches endpoints to Service.

func (*Config) Add

func (c *Config) Add(path string, method string, service string)

Add links an endpoint to a Service by name. If the path does not end with a slash and an asterisk ("/*"), only requests that match the path EXACTLY will be handled by the Service. Paths ending with "/*" is considered as a prefix.

For example:

"/api/echo" can be handled by "/api/echo" or "/api/*", but not "/api" or "/".

If multiple prefixes exist, the prefix that matches the most will be the handler.

For example:

"/api/foo/bar" will be handled by "/api/foo/*" but not "/api/*".

The Service name of an endpoint should be as specific as possible and should not contain asterisk (*).

func (*Config) Get

func (c *Config) Get(path string, method string) string

Get gets service name of the specific path and method.

type Context

type Context struct {
	// Request is the pointer to the http.Request.
	Request *http.Request
	// StatusCode holds the status code of the response.
	StatusCode int
	// Response holds the response body.
	Response []byte
	// Header holds HTTP headers in the response.
	Header http.Header
	// Data is a map that holds data of any type for value exchange between middlewares and main handler.
	Data map[string]interface{}
	// Logger is the current logger used in this context.
	Logger logger.Logger
	// contains filtered or unexported fields
}

Context is the context of a request.

func (*Context) GetServiceName

func (c *Context) GetServiceName() string

GetServiceName gets Service name of the request.

func (*Context) Interrupt

func (c *Context) Interrupt()

Interrupt stops the following handlers from executing, but does not stop the current handler. This method can be used in either pre-/post-processors or the main handler. Calling this method multiple times does not have side effects.

func (*Context) Next

func (c *Context) Next()

Next continues with the next handler, and will return if the following handlers have been run.

type Endpoint

type Endpoint struct {
	Path   string
	Method string
}

Endpoint is a struct of path and method.

type Handler

type Handler func(context *Context)

Handler is a function that handles the Service.

type Server

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

Server is a struct for HTTP router.

func Default

func Default() *Server

Default creates a Server with default configurations.

func (*Server) AttachLogger

func (s *Server) AttachLogger(logger logger.Logger)

AttachLogger attaches logger to the Server.

func (*Server) Register

func (s *Server) Register(name string, handler Handler)

Register registers a service.

Service is the configuration of one Service. The key is the identifier of the Service, separated by dots, with parent Service before sub Service. For example: "foo.bar.baz".

The value is the handler function of a Service.

A Service can be handled by a more generic Service name (the request of which can be forwarded to other Service). For example: "foo.bar" can handle "foo.bar.baz" requests. But "foo.bar.baz" cannot handle "foo.bar".

An asterisk (*) means a Service handler for all Service, if there is no other Service that are more specific.

func (*Server) RemoveErrorHandler

func (s *Server) RemoveErrorHandler(status int)

RemoveErrorHandler removes error handler of the given HTTP status code.

func (*Server) Run

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

Run starts the server with the current Config.

func (*Server) RunWithShutdown

func (s *Server) RunWithShutdown(addr string, shutdownTimeout time.Duration) error

RunWithShutdown starts the server with the current Config. It catches a SIGINT or SIGTERM as shutdown signal.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP serves HTTP requests.

func (*Server) SetErrorHandler

func (s *Server) SetErrorHandler(status int, handler Handler)

SetErrorHandler sets error handler of the given HTTP status code.

func (*Server) UseConfig

func (s *Server) UseConfig(config Config)

UseConfig applies Config to the Server.

func (*Server) UseMiddleware

func (s *Server) UseMiddleware(handler Handler)

UseMiddleware registers a middleware.

func (*Server) UseMiddlewares

func (s *Server) UseMiddlewares(handlers ...Handler)

UseMiddlewares registers middlewares.

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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