Scaffolding game servers & quick start development

series

  1. Cloud native project practice DevOps(GitOps)+K8S+BPF+SRE, from 0 to 1 using Golang to develop production-grade Mahjong game server — Part 1

introduce

This will be a complete, fully implemented Golang game server development tutorial series for DevOps/GitOps and cloud processes on Kubernetes.

This series of tutorials is a complete teardown of the open source Nanoserver project, designed to help you get started on the Golang server backend. Understand the essence of Golang development through practice — Share memory by communication.

The project may also involve work on Linux performance tuning (BPF related tools) and system assurance (SRE).

Scaffolding project

  • Scaffolding is based onnanoserverI pulled it out to help you understand this quicklyMahjong ServerHow it was built.
  • We firstMonomer architectureUnderstand the whole business -> and thenDistributed Nano Server + Micro serviceStep by Step.
  • Demo: go – mahjong – server

Based on review of

Go Modules

My local environment:

go version
# go version go1.14.14 darwin/amd64
Copy the code

go mod help

The Go mod provides access to modules operations.

Note that all go commands have built-in support for modules, not just ‘go mod’. For example, routine dependency adding, removing, upgrading, and downgrading should be done using ‘go get’. For an overview of module functionality, see ‘Go Help Modules’.

Usage:

go mod <command> [arguments]
Copy the code
  • downloadDownload the module to the local cache
  • editEdit go.mod by tool or script
  • graphPrint the module dependency diagram
  • initInitializes the new module in the current directory
  • tidyAdd missing content and remove unused modules
  • vendorMake dependent copies of third-party dependencies (Vendored)
  • verifyVerify that the dependency has the expected content
  • whyExplain why you need packages or modules

Use Go help mod < command > to get more information about the command.

Basic structure of scaffold

├ ─ ─ configs# config file│ ├─ Config. ├─ DB# Database (XORM) dependencies│ ├─ Model │ ├─ struct.go# database schema│ ├ ─ ─ const. Go │ ├ ─ ─ logger. Go │ ├ ─ ─ model. Go ├ ─ ─ internal │ ├ ─ ─ game# Game Server (Nano)│ │ ├ ─ ─ crypto. Go │ │ ├ ─ ─ game. Go │ │ ├ ─ ─ manager. Go │ ├ ─ ─ the web# Web server (providing API)│ │ ├─ Web. Go ├─ PKG# Project base pack│ ├ ─ ─ algoutil# Common utility functions│ ├── Heavy Metal Flag. Go │ ├─ CryptoMd5 rsa sha1 x509 base64│ │ ├─ Crypto. Go │ ├─ Errutil# Unified management of error codes and error messages in game server│ │ ├ ─ ─ code. Go │ │ ├ ─ ─ errutil. Go │ ├ ─ ─ whitelistWhitelist validation tool function│ ├─ White_List. Go ├─ Protocol# Agreement (release all games)
│   ├── web.go
├── main.go # entry
Copy the code

Etaphserver Basic startup process

Everything start with main.go

Loading a Configuration File

configs/config.toml

  • coreCore Base Configuration
  • webserverWeb Server Configuration
  • game-serverGame Server Configuration
  • databaseDatabase Configuration
  • whitelistWhitelist Configuration
  • updateThe client updates the configuration

Start the Game Server

game.Startup()

  1. According to the configurationconfig.toml, print relevant startup information:
    • Current version of the game server
    • Whether to force update
    • Current heartbeat interval
  2. Business function configuration (e.g.Room card set)
  3. Register game business Logic (Nano Components)
    • The player applies to join the club
    • Create a table
    • Returns card table data by table number
    • Set the table data corresponding to the table number
    • Check if the logged in player is playing before closing the app
    • After the network is disconnected, reconnect to the network
    • Network disconnect, if found that the current is in the room, after the ReConnect to re-enter, ramadhin ramadhin is before
    • Re-enter the room after the application exits
    • Richard card end
    • On the lack of
    • A player has requested to dismiss the room
    • Player voice messages
    • Handling kick out player and reset player messages (from HTTP)
  4. Register the game packet encryption pipe
    • pipeline(Inbound & Outbound)
  5. Start the Nano Server according to the Settings.
    • WithPipeline
    • WithHeartbeatInterval
    • WithLogger
    • WithSerializer
    • WithComponents

Start the Web Server

web.Startup()

  1. Database Setup (XORM)
    • DSNDatabase connection string
    • ShowSQLWhether to display the produced Sql statement
    • MaxIdleConnMaximum free connection
    • MaxOpenConnMaximum open connection < MaxIdleConn
    • syncSchemaXorm synchronizes the Model to the database table structure
    • async write channelData is inserted into the pipe asynchronously to persist data
    • async update channelData asynchronously updates the pipeline, persisting data
    • timingpingDatabase, keep the connection pool connection
  2. Enable whitelist (risk control related functions)
  3. API Service Registration (Business related Interface)
    • The login
    • The number of registered
    • The number of active
    • At the same time in the informant, table number
    • retained
    • Room card consumption,
    • Reset player’s unfinished room status
    • Set room card consumption
    • News broadcast
    • kicking
    • Online information
    • Players top-up
    • Player information query
  4. Whether to enablehttp.ListenAndServeTLS
  5. Graceful Shutdown(Do some cleanup before closing)
    • syscall.SIGINT
    • syscall.SIGQUIT
    • syscall.SIGKILL

At the same time, run microservices in Kubernetes. We need to deal with the termination signal from Kubernetes. The right way to do this is:

  1. Listening to theSIGINT.SIGTERM
  2. After receiving the signal, put the service in unhealthy mode (/healthThe route should return a status code4xx.5xx)
  3. Add a grace period before closing to allowkubernetesRemove your application from the load balancer
  4. Close the server and all open connections
  5. Shutdown

Mind maps

Quick start development

Docker Compose starts MySql locally with one click

The previous article has been introduced in detail, here is not repeated ha.

Cloud native project practice DevOps(GitOps)+K8S+BPF+SRE, from 0 to 1 using Golang to develop production-grade Mahjong game server — Part 1

Docker - compose - f docker - compose. Mysql. 5.7 yaml up# -dDocker - compose - f docker - compose. Mysql. 5.7 yaml downCopy the code

Use Air for local development

☁️ Live reload for Go apps

go get -u github.com/cosmtrek/air
Copy the code

Development (project root) :

air
Copy the code

Use the VS code-go plug-in to debug the program

VSCode-Go Debugging

The installationDelve

  1. Open theThe command panel(Windows/Linux: Ctrl+Shift+P; OSX: Shift + Command + P),

Select Go: Install/Update Tools and then select DLV

Start debugging

  1. Open what you want to debugpackage mainThe source file (source file) or test file (test file)
  2. Use either of the following methods for debugging:
    • Open theThe command panel, the choice ofDebug: Start DebuggingAnd then selectGo.
    • Open the debug window (Windows/Linux: Ctrl+Shift+D; OSX: Shift+Command+D), then clickRun and DebugsAnd then selectGo.
    • Choose Run > Start Debugging from the main menu

I am weishao wechat: uuhells123 public number: hackers afternoon tea add my wechat (mutual learning exchange), pay attention to the public number (for more learning materials ~)Copy the code