Categorygithub.com/yankawayu/go-socket
modulepackage
0.0.0-20230902093355-ee071d19ec2c
Repository: https://github.com/yankawayu/go-socket.git
Documentation: pkg.go.dev

# README

go-socket Build Status Go Report Card Go Reference

Go-socket is an open-source, high-performance socket framework for building backend services in Golang.

The protocol of Go-socket is called GOSOC, which is similar to MQTT. Since MQTT is designed for the Internet of Things(loT), it's extremely efficient. For more information, please read GOSOC.

Together with go-socket-client, you will be able to build a server/client system communicating with each other using sockets.

The Go-socket is designed to work independently on each server as long as there are common databases to store data. Therefore, you can deploy it on as many servers as you want, so that it can hold on up to 1 million users at the same time. Just put a load balancer like nginx in front of those servers to balance all the requests from clients. The following diagram describe the deployment:

architecture

Getting started

Getting Go-socket

With Go module support, simply add the following import

import "github.com/YanKawaYu/go-socket"

to your code, and then go [build|run|test] will automatically fetch the necessary dependencies.

Otherwise, run the following Go command to install the go-socket package:

$ go get -u github.com/YanKawaYu/go-socket

If you hadn't created a module, make sure you run this command first

go mod init Example

Running Go-socket

After you import go-socket package, you can start with a simplest example like the following example.go:

package main

import (
	"github.com/yankawayu/go-socket"
)

func main() {
	appConfig := &gosocket.AppConfig{
		TcpAddr:   "0.0.0.0",
		TcpPort:   8080,
		TlsEnable: false,
	}
	fastLog := gosocket.GetFastLog("app.access", false)
	// listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
	gosocket.Run(appConfig, nil, gosocket.GetLog(false), fastLog)
}

Make sure you create a runtime directory for logging and then use the Go command to run the demo:

# create a directory for logging
$ mkdir -m 777 runtime
# run example.go and access the server with telnet
$ go run example.go
$ telnet 127.0.0.1 8080

Go versions

Since we use go.uber.org/zap as the log component, it only supports the two most recent minor versions of Go. Therefore, the requirement of the Go version for this framework is the same.

Learn more examples

Learn and practice more examples, please read the Go-socket Quick Start which includes API examples

Source code

There are several major classes in the framework. Their relationships can be explained through the following diagram.

go-socket

For more details, you should see the comments in the source code.

Contributing

For now, I'm the only one that maintaining Go-socket. Any pull requests, suggestions or issues are appreciated!

License

Go-socket is under the MIT license. See the LICENSE file for details.

The encoding and decoding part of this software is modified from this repository. Thanks to the author Zhangxuan,Xu.

What's next

The ultimate goal of this project is to support a high performance IM server developed by Go. I would like to release it in the future.

# Packages

No description provided by the author
No description provided by the author

# Functions

GetClientPool is the only way to get the single ClientPool instance 获取连接池单例.
No description provided by the author
No description provided by the author
GetRestartManager get the single instance RestartManager 获取重启管理器.
InitGracefulRestart is used to initialize graceful restart If you don't call this function, the server won't be able to restart itself through signal.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
NewClient create a new client by providing the ip, port of the server and whether to use tls 创建一个新的客户端连接.
No description provided by the author
No description provided by the author
No description provided by the author
NewServer Create a new server 创建一个新的服务器.
No description provided by the author
No description provided by the author
No description provided by the author
ProcessPayloadWithData process the request payload This function will match the request to a certain action under the controller by reflecting.
Router Register a controller to its corresponding name 注册Controller以及对应的名字.
Run start the server This is the entry point of the whole framework The appConfig is used to configure the server The user is used to customize the user identification process The log is used to log any errors happens during the process The fastLog is used to log any requests received by the server The requests can be very frequent therefore using the fast logger will make sure the performance is high.

# Constants

No description provided by the author
No description provided by the author
No description provided by the author
Format error, always return with a message.
Unknown internal error, always found with a log record under runtime directory.
These are all the status codes that embedded in ResponseBody 返回状态码.

# Variables

No description provided by the author

# Structs

App is the entry class to start the server.
AppConfig Server configuration 服务器配置.
AuthUser Default login auth class, should inherit this class to implement concrete auth logic 默认登陆验证父类,继承后实现具体登陆逻辑.
Client is a class responsible for connecting to the server by socket Make sure the port and the isTls value are the same as the ones on server.
ClientConn is used to handle individual valid connection coming to the server It contains three threads including Reading thread, writing thread and handling thread Reading thread is used to read and decode input data into messages, then put those messages into Handling thread Writing thread is used to send all the messages back as output data Handling thread is used to process all the incoming messages from Reading thread and generate response messages.
ClientPool is used to store all the connections on the server It follows singleton pattern which means there should be only one instance Please use GetClientPool to get the instance Since the pool will be accessed by different threads, it is required to use sync.RWMutex to avoid conflict.
No description provided by the author
Connection is a wrapper for net.Conn.
Controller the base class of all controllers Controller基类,用于共同的属性和方法.
FastLog is a wrapper for zap.Logger This class is to make sure the framework won't have too much dependency on go.uber.org/zap The FastLog has a much higher performance than the Log, make sure you choose the right one according to your situation.
Job is used to store the message that is about to be sent out.
No description provided by the author
Listener is a wrapper of net.TCPListener.
Log is a wrapper for zap.SugaredLogger This class is to make sure the framework won't have too much dependency on go.uber.org/zap.
MessageHandler is the class responsible for processing messages from client and generating responses messages This class is an essential member of ClientConn, it handles most of the time-consuming works.
ResponseBody the format of the server response 返回数据.
RestartManager is the class to manage the server's restart process It will listen to two types of signals: syscall.SIGUSR1 the server will shut down gracefully syscall.SIGUSR2 the server will restart gracefully, this is often used when the server needs to be upgraded.
Server is the class to handle incoming requests by serving and listening.
SocketClientConn is a class inside Client responsible for connecting to the server.
Timer is a utility class for the framework.

# Interfaces

No description provided by the author
IConnectProvider is used to provide connect info.
IController the interface that all controllers should be implemented Controller接口,用于多态.
IFastLogger is an interface for logger class in the framework The purpose of defining this interface is to make sure the framework won't heavily rely on go.uber.org/zap All these functions come from zap.Logger 用于打印访问日志.
ILogger is an interface for logger class in the framework The purpose of defining this interface is to make sure the framework won't heavily rely on go.uber.org/zap All these functions come from zap.SugaredLogger ILogger has many more functions than IFastLogger, since ILogger values function more than performance 用于打印普通日志,包括信息、错误等.
No description provided by the author
No description provided by the author
IUserError Whenever you panic an error that implements this interface in the action, the response message will be the return result of ShowError For example, {"status":4, "message":"this is an error"} You will find the code in ProcessPayloadWithData function 实现了这个接口的错误,panic的时候,就会返回4,同时提示ShowError的内容作为错误消息.

# Type aliases

No description provided by the author
GetDataCallback is the callback used by GetData function.
OnRestartSuccess is called under the following situations syscall.SIGUSR1 the server is about to stop syscall.SIGUSR2 the child process has started successfully This callback is used to clear the remaining resources SIGUSR1时为子进程启动成功的回调,SIGUSR2时为当前进程停止的回调,此函数应用于资源的释放.
No description provided by the author
No description provided by the author