Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add more comments #127

Merged
merged 3 commits into from
Aug 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
71 changes: 46 additions & 25 deletions pkg/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,51 +35,72 @@ import (
"go.uber.org/zap"
)

// Field is an alias of zap.Field
type Field = zap.Field

var (
String = zap.String
Bytes = zap.ByteString
// String is an alias of zap.String
String = zap.String
// Bytes is an alias of zap.Bytes
Bytes = zap.ByteString
// Duration is an alias of zap.Duration
Duration = zap.Duration

Int8 = zap.Int8
// Int8 is an alias of zap.Int8
Int8 = zap.Int8
// Int32 is an alias of zap.Int32
Int32 = zap.Int32
Int = zap.Int
// Int is an alias of zap.Int
Int = zap.Int
// Int64 is an alias of zap.Int64
Int64 = zap.Int64

Uint8 = zap.Uint8
// Uint8 is an alias of zap.Uint8
Uint8 = zap.Uint8
// Uint32 is an alias of zap.Uint32
Uint32 = zap.Uint32
Uint = zap.Uint
// Uint is an alias of zap.Uint
Uint = zap.Uint
// Uint64 is an alias of zap.Uint64
Uint64 = zap.Uint64

// Float64 is an alias of zap.Float64
Float64 = zap.Float64
Any = zap.Any
// Any is an alias of zap.Any
Any = zap.Any
)

//default logger
// defaultLogger default logger for internal used
var defaultLogger *Logger

// Logger logger definition
type Logger struct {
logger *zap.Logger
level zap.AtomicLevel
}

// Config log configs
type Config struct {
Dir string
Name string
// Dir log output directory
Dir string
// Name log output file name
Name string
// Level log level
Level string

CallerSkip int
// CallerSkip log depth
CallerSkip int
// FlushInterval log flush interval
FlushInterval time.Duration

Debug bool
WatchConfig bool
EnableAsyncLog bool
// Debug log mode, default true
Debug bool
// WatchConfig whether watch config file changes
WatchConfig bool
// EnableAsyncLog whether flush log async
EnableAsyncLog bool
// DisableStacktrace where log stack details if run into error
DisableStacktrace bool

// 日志输出文件最大长度,超过改值则截断
MaxSize int
MaxAge int
// MaxSize max size of log file, it'll rotate log automatically if exceed the max size
MaxSize int
// MaxAge max duration of store logs
MaxAge int
// MaxBackup max files of backup logs
MaxBackup int
}

Expand Down Expand Up @@ -140,7 +161,7 @@ func defaultConfig() *Config {
}
}

// New return a pointer of Logger
// New returns a Logger instance
func New(config *Config) *Logger {
if config == nil {
config = defaultConfig()
Expand Down Expand Up @@ -226,7 +247,7 @@ func assembleFields(ctx context.Context, fields ...Field) []Field {
return fs
}

// rotate rotate log
// rotate rotate log according to the predefined polices
func rotate(config *Config) io.Writer {
return &lumberjack.Logger{
Filename: fmt.Sprintf("%s/%s", config.Dir, config.Name),
Expand Down
28 changes: 19 additions & 9 deletions pkg/server/http/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,27 +24,37 @@ import (
"github.com/gin-gonic/gin"
)

// ClientConfig http client config
type ClientConfig struct {
HostURL string
Timeout time.Duration
// HostURL peer service host
HostURL string
// Timeout request timeout
Timeout time.Duration
// SlowRequestDuration slow request timeout
SlowRequestDuration time.Duration

// EnableDebug trace request details
EnableDebug bool

Key string
// Key client key
Key string
// Secret signature secret
Secret string
}

// ServerConfig http server config
type ServerConfig struct {
// Addr server addr, like :8080 or 127.0.0.1:8080
Addr string

// Timeout request timeout
Timeout time.Duration
Mode string

// Mode server mode: release or debug
Mode string
// SlowRequestDuration slow request timeout
SlowRequestDuration time.Duration
WatchConfig bool
// WatchConfig whether watch config file changes
WatchConfig bool
}

// DefaultServerConfig default server configs, for start http server out of box
func DefaultServerConfig() *ServerConfig {
return &ServerConfig{
Addr: "0.0.0.0:10000",
Expand Down
5 changes: 3 additions & 2 deletions pkg/server/http/middlewares/cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,15 @@ import (
"github.com/gin-gonic/gin"
)

// CORSConfig is an alias of cors.Config
type CORSConfig cors.Config

// default cors handler
// DefaultCORS default cors handler
func DefaultCORS() gin.HandlerFunc {
return cors.Default()
}

// customer cors handler by config
// NewCORS customer cors handler by config
func NewCORS(config CORSConfig) gin.HandlerFunc {
return cors.New(cors.Config(config))
}
1 change: 1 addition & 0 deletions pkg/server/http/middlewares/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"github.com/gin-gonic/gin"
)

// Logger log request details
func Logger(config *config.ServerConfig) gin.HandlerFunc {
return func(c *gin.Context) {
now := time.Now()
Expand Down
3 changes: 2 additions & 1 deletion pkg/server/http/middlewares/recovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ var (
slash = []byte("/")
)

// Recovery recover application and log panic details once it panics
func Recovery() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
Expand Down Expand Up @@ -117,7 +118,7 @@ func source(lines [][]byte, n int) []byte {
return bytes.TrimSpace(lines[n])
}

// function returns, if possible, the name of the function containing the PC.
// function returns, if possible, the name of the function containing the PC
func function(pc uintptr) []byte {
fn := runtime.FuncForPC(pc)
if fn == nil {
Expand Down
1 change: 1 addition & 0 deletions pkg/server/http/middlewares/trace.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (
"github.com/gin-gonic/gin"
)

// Trace trace incoming request details
func Trace(config *config.ServerConfig) gin.HandlerFunc {
return func(c *gin.Context) {
span, ctx := trace.StartSpanFromContext(
Expand Down
8 changes: 5 additions & 3 deletions pkg/server/http/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,14 @@ import (
_ "go.uber.org/automaxprocs"
)

// Server http server
type Server struct {
*gin.Engine
Server *http.Server
config *config.ServerConfig
}

// New returns a http server instance
func New(cfg *config.ServerConfig) *Server {
if cfg == nil {
cfg = config.DefaultServerConfig()
Expand All @@ -58,7 +60,7 @@ func New(cfg *config.ServerConfig) *Server {
return srv
}

//start server
// Start server
func (s *Server) Start() net.Addr {
listener, err := net.Listen("tcp", s.config.Addr)
if err != nil {
Expand All @@ -84,12 +86,12 @@ func (s *Server) Start() net.Addr {
return listener.Addr()
}

// shutdown server graceful
// Stop shutdown server graceful
func (s *Server) Stop(ctx context.Context) error {
return s.Server.Shutdown(ctx)
}

// upgrade http to websocket
// Upgrade upgrade http to websocket
func (s *Server) Upgrade(ws *websocket.WebSocket) gin.IRoutes {
return s.GET(ws.Path, func(c *gin.Context) {
ws.Upgrade(c.Writer, c.Request)
Expand Down
4 changes: 4 additions & 0 deletions pkg/server/http/websocket/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ import (
"github.com/gorilla/websocket"
)

// WebSocketHandler ws callback handler
type WebSocketHandler func(*WebSocket)

// WebSocket ws definition
type WebSocket struct {
Path string
Handler WebSocketHandler
Expand All @@ -35,6 +37,7 @@ type WebSocket struct {
*websocket.Conn
}

// NewWebSocket returns a WebSocket instance
func NewWebSocket(path string, handler WebSocketHandler) *WebSocket {
return &WebSocket{
Path: path,
Expand All @@ -43,6 +46,7 @@ func NewWebSocket(path string, handler WebSocketHandler) *WebSocket {
}
}

// Upgrade upgrade http to WebSocket
func (ws *WebSocket) Upgrade(w http.ResponseWriter, r *http.Request) {
conn, err := ws.Upgrader.Upgrade(w, r, nil)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions pkg/server/rpc/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import (
"google.golang.org/grpc"
)

// Client grpc client definition
type Client struct {
conn *grpc.ClientConn
config *config.ClientConfig
Expand All @@ -44,6 +45,7 @@ type Client struct {
unaryInterceptors []grpc.UnaryClientInterceptor
}

// New returns a Client instance
func New(config *config.ClientConfig) *Client {
cli := &Client{
config: config,
Expand Down Expand Up @@ -89,7 +91,6 @@ func New(config *config.ClientConfig) *Client {
}

// ChainUnaryClient creates a single interceptor out of a chain of many interceptors.
//
// Execution is done in left-to-right order, including passing of context.
// For example ChainUnaryClient(one, two, three) will execute one before two before three.
func (c *Client) ChainUnaryClient() grpc.UnaryClientInterceptor {
Expand All @@ -113,7 +114,6 @@ func (c *Client) ChainUnaryClient() grpc.UnaryClientInterceptor {
}

// Chain creates a single interceptor out of a chain of many interceptors.
//
// WithUnaryServerChain is a grpc.Client dial option that accepts multiple unary interceptors.
// Basically syntactic sugar.
func (c *Client) WithUnaryServerChain() grpc.DialOption {
Expand Down
38 changes: 24 additions & 14 deletions pkg/server/rpc/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,25 @@ import (
"time"
)

// ServerConfig rpc server config
type ServerConfig struct {
// Addr server addr,it may be ":8080" or "127.0.0.1:8080"
Addr string

Timeout time.Duration
IdleTimeout time.Duration
MaxLifeTime time.Duration
ForceCloseWait time.Duration

// Timeout rpc request timeout
Timeout time.Duration
// GRPC ServerParameters
IdleTimeout time.Duration
MaxLifeTime time.Duration
ForceCloseWait time.Duration
KeepAliveInterval time.Duration
KeepAliveTimeout time.Duration

// SlowRequestDuration slow rpc request timeout
SlowRequestDuration time.Duration
WatchConfig bool
// WatchConfig whether watch config file changes
WatchConfig bool
}

// DefaultServerConfig default server config for starting rpc server out of box
func DefaultServerConfig() *ServerConfig {
return &ServerConfig{
Addr: "0.0.0.0:20812",
Expand All @@ -50,20 +54,26 @@ func DefaultServerConfig() *ServerConfig {
}
}

// ClientConfig rpc client configs
type ClientConfig struct {
// DialTimeout dial rpc server timeout
DialTimeout time.Duration
Block bool
Balancer string
Target string

// Block dial mode: sync or async
Block bool
// Balancer client balancer, default round robbin
Balancer string
// Target rpc server endpoint
Target string
// Timeout rpc request timeout
Timeout time.Duration

// GRPC ClientParameters
KeepAliveInterval time.Duration
KeepAliveTimeout time.Duration

// SlowRequestDuration client slow request timeout
SlowRequestDuration time.Duration
}

// DefaultClientConfig default client config for starting rpc client out of box
func DefaultClientConfig() *ClientConfig {
return &ClientConfig{
DialTimeout: 5 * time.Second,
Expand Down
1 change: 1 addition & 0 deletions pkg/server/rpc/interceptors/breaker.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"google.golang.org/grpc"
)

// GoogleSREBreaker breaker based on google sre. It rejects request adaptively based on server response
func GoogleSREBreaker(breakers *breaker.BreakerGroup) grpc.UnaryClientInterceptor {
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
return breakers.Do(
Expand Down