web

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2021 License: MIT Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// PermissionGuest is guest(unauthorized)
	PermissionGuest = 0
	// PermissionNormal is normal
	PermissionNormal = 1
)

Variables

View Source
var DefaultHttpClient = &Client{
	Timeout:   time.Second * 2,
	userValue: make(utils.KVPairs, 0),
}

DefaultHttpClient is the default http client for server to server communication

Functions

func RegisterHeaderReceivedHandler

func RegisterHeaderReceivedHandler(funcID string, h HeaderReceivedHandler)

RegisterHeaderReceivedHandler registers HeaderReceivedHandler function with funcID

func RegisterMiddleware

func RegisterMiddleware(middlewareID string, m Middleware)

RegisterMiddleware registers Middleware function with middlewareID

func RegisterService

func RegisterService(serviceID string, f Handler)

RegisterService registers Handler function with serviceID

Types

type Authentication

type Authentication struct {
	UserID string `json:"userId"      bson:"user_id"        sql:"user_id"`

	AccessToken string `json:"accessToken" bson:"access_token"   sql:"access_token"`
	Permission  uint8  `json:"permission"  bson:"permission"     sql:"permission"`
	// contains filtered or unexported fields
}

Authentication represents basic authentication information

func AuthenticationFromAccessToken

func AuthenticationFromAccessToken(token string) (auth *Authentication)

func NewAuthentication

func NewAuthentication(l ...int) *Authentication

func (*Authentication) HasPermission

func (auth *Authentication) HasPermission(perm uint8) bool

HasPermission returns true if user has given permission level

func (*Authentication) ID

func (auth *Authentication) ID() string

ID returns user ID

type Client

type Client struct {
	Timeout time.Duration
	// contains filtered or unexported fields
}

Client represents http client for server to server communication

func (*Client) Delete

func (c *Client) Delete(url string, respBody interface{}) (statusCode int, err error)

func (*Client) Do

func (c *Client) Do(req *fasthttp.Request, resp *fasthttp.Response) (err error)

func (*Client) Get

func (c *Client) Get(url string, args *fasthttp.Args, respBody interface{}) (statusCode int, err error)

func (*Client) Post

func (c *Client) Post(url string, args *fasthttp.Args, respBody interface{}) (statusCode int, err error)

func (*Client) Put

func (c *Client) Put(url string, args *fasthttp.Args, respBody interface{}) (statusCode int, err error)

func (*Client) Request

func (c *Client) Request(url string, method string, args *fasthttp.Args, respBody interface{}) (statusCode int, err error)

type Ctx

type Ctx interface {
	// Context returns the internal context of this API processing
	Context() context.Context
	// ConstStringValue returns const string parameter value defined in controller
	ConstStringValue(name string) string
	// ConstIntValue returns const int parameter value defined in controller
	ConstIntValue(name string) int
	// StatusOk sets status code to 200
	StatusOk() Ctx
	// StatusCreated sets status code to 201
	StatusCreated(location string) Ctx
	// StatusAccepted sets status code to 202
	StatusAccepted() Ctx
	// StatusNonAuthoritativeInfo  sets status code to 203
	StatusNonAuthoritativeInfo() Ctx
	// StatusNoContent sets status code to 204
	StatusNoContent() Ctx
	// Error sets status code with error message (do not set 2xx/3xx)
	Error(statusCode int, msg ...interface{}) Ctx
	// StatusBadRequest sets status code to 400
	StatusBadRequest(param ...interface{}) Ctx
	// StatusUnauthorized sets status code to 401
	StatusUnauthorized() Ctx
	// StatusForbidden sets status code to 403
	StatusForbidden(msg ...interface{}) Ctx
	// StatusNotFound sets status code to 404
	StatusNotFound() Ctx
	// StatusInternalServerError sets status code to 500
	StatusInternalServerError(msg ...interface{}) Ctx
	// StatusServiceUnavailable sets status code to 503
	StatusServiceUnavailable(msg ...interface{}) Ctx
	// SetResponseValue sets/adds a pair of key-value append to response body
	SetResponseValue(key string, value interface{})
	// SysLogf writes system log
	// system logs are used for technicians to investigate warns and errors
	// no need to consider log level because log level will be automatically set
	// if no errors occurred and status code is set to 2xx/3xx, log level is info
	// if no errors occurred and status code is set to 4xx, log level is warn
	// if any errors occurred or status code is set to 5xx, log level is error
	SysLogf(format string, args ...interface{}) Ctx
	// GameLog writes game log
	// game logs are used to track user behavior history
	// game logs are for KPI analysis, customer service, etc.
	GameLog(action string, fields map[string]interface{}, args ...interface{}) Ctx
	// Assert throw a fatal error if the value of ok is not true
	Assert(ok bool, format string, args ...interface{}) Ctx
	// Cache returns reference of cache instance by id
	// cache instance with an id is defined in controllers
	Cache(id ...string) (plugin *plugins.Cache)
	// Redis returns reference of redis client by id
	// redis client with an id is defined in controllers
	Redis(id ...string) (plugin *plugins.Redis)
	// Mongo returns reference of mongodb client with default database
	// mongodb client with an id is defined in controllers
	Mongo(database ...string) (plugin *plugins.Mongo)
	// MySQL returns reference of mysql client with default database
	// mysql client with an id is defined in controllers
	MySQL(database ...string) (plugin *plugins.MySQL)
	// Sqlite returns reference of sqlite
	// sqlite with an id is defined in controllers
	Sqlite(database ...string) (plugin *plugins.Sqlite)
	// MasterTable find and returns master table by table name
	MasterTable(tableName string, mux ...string) plugins.MasterTable
	// HasError returns true if no errors occurred and status code is 2xx/3xx
	HasError() bool
	// HttpClient returns the default http client that used for server-server communication
	HttpClient() *Client
	// Now returns the time when request came
	Now() time.Time

	context.Context
	// contains filtered or unexported methods
}

Ctx is interface of ctx implements

type Gate

type Gate struct {
	Config *GateConfig
	// contains filtered or unexported fields
}

Gate represents web API proxy server

func NewGate

func NewGate(engine engine.Interface, config GateConfig) (*Gate, error)

func (*Gate) ID

func (g *Gate) ID() string

func (*Gate) Serve

func (g *Gate) Serve(ctx context.Context) (err error)

Serve is non-blocking

func (*Gate) Stop

func (g *Gate) Stop()

type GateConfig

type GateConfig struct {
	ServerConfig `yaml:",inline"`
	Gateways     []struct {
		ServerName string   `yaml:"server_name" default:""`
		LBClients  []string `yaml:"lb_clients"`
	} `yaml:"gateways"`
	Timeout time.Duration `yaml:"timeout" default:"2s"`
}

type Handler

type Handler func(ctx Ctx)

Handler does process http API business logic

type HeaderReceivedHandler

type HeaderReceivedHandler func(header *fasthttp.RequestHeader) fasthttp.RequestConfig

HeaderReceivedHandler is function to process request header

type Middleware

type Middleware func(Handler) Handler

Middleware represents middleware function type

func (Middleware) Apply

func (m Middleware) Apply(f Handler) Handler

Apply applies middleware to handler

func (Middleware) Left

func (m Middleware) Left(right Middleware) Middleware

Left left combines another middleware

func (Middleware) Right

func (m Middleware) Right(left Middleware) Middleware

Right right combines another middleware

type Server

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

Server represents web API server

func NewServer

func NewServer(engine engine.Interface, config ServerConfig) (newServer *Server, err error)

NewServer returns a new hayabusa web server pointer

func (*Server) ID

func (server *Server) ID() string

func (*Server) RegisterPluginCacheMiddleware

func (server *Server) RegisterPluginCacheMiddleware(id string)

func (*Server) RegisterPluginMongoMiddleware

func (server *Server) RegisterPluginMongoMiddleware(id string)

func (*Server) RegisterPluginMySQLMiddleware

func (server *Server) RegisterPluginMySQLMiddleware(id string)

func (*Server) RegisterPluginRedisMiddleware

func (server *Server) RegisterPluginRedisMiddleware(id string)

func (*Server) RegisterPluginSqliteMiddleware

func (server *Server) RegisterPluginSqliteMiddleware(id string)

func (*Server) Serve

func (server *Server) Serve(ctx context.Context) (err error)

Serve is non-blocking

func (*Server) SetGameLogger

func (server *Server) SetGameLogger(l plugins.Logger) *Server

func (*Server) SetSysLogger

func (server *Server) SetSysLogger(l plugins.Logger) *Server

func (*Server) Stop

func (server *Server) Stop()

type ServerConfig

type ServerConfig struct {
	ID                 string        `yaml:"id" required:"true"`
	HttpVersion        string        `yaml:"http_version" default:"1.1"`
	Network            string        `yaml:"network" default:"tcp"`
	Address            string        `yaml:"address" default:":8088"`
	UseTLS             bool          `yaml:"use_tls" default:"false"`
	CertFile           string        `yaml:"cert_file"`
	KeyFile            string        `yaml:"key_file"`
	Concurrency        int           `yaml:"concurrency" default:"8192"`
	MaxConnectionPerIP int           `yaml:"max_connection_per_ip" default:"1024"`
	ReadTimeout        time.Duration `yaml:"read_timeout" default:"0"`
	WriteTimeout       time.Duration `yaml:"write_timeout" default:"0"`
	MaxRequestBodySize int           `yaml:"max_request_body_size" default:"1024"`
	CompressLevel      int           `yaml:"compress_level" default:"0"`
	HandleTimeout      time.Duration `yaml:"handle_timeout" default:"0"`
	ControllerFilepath string        `yaml:"controller_filepath" default:"controller/"`
	LogLevel           string        `yaml:"log_level" default:"info"`
}

Jump to

Keyboard shortcuts

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