Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Nakama
https://github.com/heroiclabs/nakama
Admin
Distributed server for social and realtime games and apps.
Tokens:
133,504
Snippets:
1,032
Trust Score:
9.7
License:
Apache-2.0
Update:
1 month ago
Context
Chat
Benchmark
56.18
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Installation: go get command Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/heroiclabs/sql-migrate/README.md Use this command to fetch the sql-migrate package. ```bash go get -v github.com/heroiclabs/nakama/sql-migrate/ ``` -------------------------------- ### Install bitset with go get Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/bits-and-blooms/bitset/README.md Use this command to install the bitset library. It fetches the latest version from the module proxy. ```bash go get github.com/bits-and-blooms/bitset ``` -------------------------------- ### Install with go get Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/go-sourcemap/sourcemap/README.md Install the sourcemap package using the Go module tool. ```shell go get -u github.com/go-sourcemap/sourcemap ``` -------------------------------- ### Install cronexpr with go get Source: https://github.com/heroiclabs/nakama/blob/master/internal/cronexpr/README.md Install the cronexpr library using the go get command. ```bash go get github.com/gorhill/cronexpr ``` -------------------------------- ### Install multierr with go get Source: https://github.com/heroiclabs/nakama/blob/master/vendor/go.uber.org/multierr/README.md Install the multierr library using the go get command. This fetches the latest version of the package. ```bash go get -u go.uber.org/multierr@latest ``` -------------------------------- ### Setup and test commands Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/jackc/pgx/v5/README.md Commands to set up the development environment and run the test suite. Requires Homebrew on macOS or a compatible package manager on Ubuntu. The 'mise trust' and 'mise install' commands install project tools, while 'mise run dev:init' initializes ports and certificates. Run './test.sh' for PostgreSQL 18 or './test.sh all' for all targets. ```sh scripts/setup-host # native macOS (Homebrew required) or Ubuntu: host packages and mise export PATH="$HOME/.local/bin:$PATH" # if mise was just installed mise trust mise install # project tools mise run dev:init # checkout ports and certificates mise run dev # start PostgreSQL 18 and the on-demand database supervisor ./test.sh # the suite against PostgreSQL 18 ./test.sh all # every target, starting and stopping each server as needed ``` -------------------------------- ### Install go.yaml.in/yaml/v3 with go get Source: https://github.com/heroiclabs/nakama/blob/master/vendor/go.yaml.in/yaml/v3/README.md Installs the yaml package for Go using the go get command. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Install cloud.google.com/go/compute/metadata Source: https://github.com/heroiclabs/nakama/blob/master/vendor/cloud.google.com/go/compute/metadata/README.md Use this command to install the metadata utility library for Google Cloud. ```bash go get cloud.google.com/go/compute/metadata ``` -------------------------------- ### Install go.uber.org/atomic with go get Source: https://github.com/heroiclabs/nakama/blob/master/vendor/go.uber.org/atomic/README.md Install the atomic package using the go get command. This is the recommended way to add the dependency to your project. ```shell $ go get -u go.uber.org/atomic@v1 ``` -------------------------------- ### Install Gorilla Mux with go get Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/gorilla/mux/README.md Use this command to install the Gorilla Mux package. Requires a correctly configured Go toolchain. ```sh go get -u github.com/gorilla/mux ``` -------------------------------- ### Setup and test commands for pgx development Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/jackc/pgx/v5/DEVELOPMENT.md Complete setup and test workflow for pgx development. Run these commands in order after installing prerequisites; the first command is only needed once per machine. ```sh scripts/setup-host # native macOS or Ubuntu host prerequisites (once per machine) export PATH="$HOME/.local/bin:$PATH" # if mise was just installed mise trust # trust this checkout's configuration mise install # tool versions from mise.toml mise run dev:init # this checkout's ports and certificates mise run dev # start PostgreSQL 18 and the on-demand database supervisor ./test.sh # the suite against PostgreSQL 18 ./test.sh all # every target; non-default servers start and stop around their tests ``` -------------------------------- ### Example using handlers.LoggingHandler and handlers.CompressHandler Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/gorilla/handlers/README.md A simple example that sets up an HTTP server with a mux, logs requests to the admin dashboard using handlers.LoggingHandler, and wraps the server with handlers.CompressHandler to gzip all responses. ```go import ( "net/http" "github.com/gorilla/handlers" ) func main() { r := http.NewServeMux() // Only log requests to our admin dashboard to stdout r.Handle("/admin", handlers.LoggingHandler(os.Stdout, http.HandlerFunc(ShowAdminDashboard))) r.HandleFunc("/", ShowIndex) // Wrap our server with our gzip handler to gzip compress all responses. http.ListenAndServe(":8000", handlers.CompressHandler(r)) } ``` -------------------------------- ### Install cronexpr with go get and go install Source: https://github.com/heroiclabs/nakama/blob/master/internal/cronexpr/cronexpr/README.md Install the cronexpr command-line utility using Go's package management. Run these commands in your terminal. ```bash go get github.com/gorhill/cronexpr go install github.com/gorhill/cronexpr ``` -------------------------------- ### Start Nakama server Source: https://github.com/heroiclabs/nakama/blob/master/README.md Starts the Nakama server and connects to the database. Run after the migration step. The server will output configuration details upon successful connection. ```shell nakama --database.address "root@127.0.0.1:26257" ``` -------------------------------- ### Install go-fuzz Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/blevesearch/segment/README.md Install go-fuzz and go-fuzz-build tools. ```bash go get github.com/dvyukov/go-fuzz/go-fuzz go get github.com/dvyukov/go-fuzz/go-fuzz-build ``` -------------------------------- ### Set up a source of migrations Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/heroiclabs/sql-migrate/README.md Defines multiple ways to source migrations: in-memory, file, packr, pkger, bindata, or http.FileSystem. Shows the typical setup before running migrations. ```go // Hardcoded strings in memory: migrations := &migrate.MemoryMigrationSource{ Migrations: []*migrate.Migration{ &migrate.Migration{ Id: "123", Up: []string{"CREATE TABLE people (id int)"}, Down: []string{"DROP TABLE people"}, }, }, } // OR: Read migrations from a folder: migrations := &migrate.FileMigrationSource{ Dir: "db/migrations", } // OR: Use migrations from a packr box migrations := &migrate.PackrMigrationSource{ Box: packr.New("migrations", "./migrations"), } // OR: Use pkger which implements `http.FileSystem` migrationSource := &migrate.HttpFileSystemMigrationSource{ FileSystem: pkger.Dir("/db/migrations"), } // OR: Use migrations from bindata: migrations := &migrate.AssetMigrationSource{ Asset: Asset, AssetDir: AssetDir, Dir: "migrations", } // OR: Read migrations from a `http.FileSystem` migrationSource := &migrate.HttpFileSystemMigrationSource{ FileSystem: httpFS, } ``` -------------------------------- ### Build and load a Nakama Go plugin Source: https://github.com/heroiclabs/nakama/blob/master/sample_go_module/README.md Compile the plugin code into a shared object file, then start the Nakama server with the --runtime.path flag pointing to the directory containing the built plugin. The server loads plugins from the specified path; ensure the database is running before starting the server. ```bash go build -buildmode=plugin -trimpath -o ./plugin_code.so ``` ```bash ./nakama --runtime.path "$HOME/plugin_code" ``` -------------------------------- ### Install glua interpreter Source: https://github.com/heroiclabs/nakama/blob/master/internal/gopher-lua/README.rst Installs the standalone GopherLua interpreter (glua) using go get. After installation, glua can be used similarly to the standard Lua interpreter. ```bash go get github.com/yuin/gopher-lua/cmd/glua ``` -------------------------------- ### Install xgo CLI tool Source: https://github.com/heroiclabs/nakama/blob/master/build/README.md Installs the xgo command-line helper tool. Ensure $GOPATH/bin is on your system path to access the executable. ```bash go install src.techknowlogick.com/xgo@latest ``` -------------------------------- ### Full mux server example Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/gorilla/mux/README.md Complete runnable example of a small mux-based server. It creates a router, registers a handler for the root path, and serves on port 8000. The handler writes "Gorilla!\n" to the response. ```go package main import ( "net/http" "log" "github.com/gorilla/mux" ) func YourHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Gorilla!\n")) } func main() { r := mux.NewRouter() // Routes consist of a path and a handler function. r.HandleFunc("/", YourHandler) // Bind to a port and pass our router in log.Fatal(http.ListenAndServe(":8000", r)) } ``` -------------------------------- ### Quick Start with SugaredLogger Source: https://github.com/heroiclabs/nakama/blob/master/vendor/go.uber.org/zap/README.md Use the SugaredLogger when performance is nice but not critical. It is 4-10x faster than other structured logging packages and provides both structured and printf-style APIs. The example shows creating a production logger, deferring Sync to flush the buffer, and logging with Infow and Infof. ```go logger, _ := zap.NewProduction() defer logger.Sync() // flushes buffer, if any sugar := logger.Sugar() sugar.Infow("failed to fetch URL", // Structured context as loosely typed key-value pairs. "url", url, "attempt", 3, "backoff", time.Second, ) sugar.Infof("Failed to fetch URL: %s", url) ``` -------------------------------- ### Install host prerequisites with scripts/setup-host Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/jackc/pgx/v5/DEVELOPMENT.md Installs host prerequisites for native macOS or Ubuntu development. On macOS it uses Homebrew and a Brewfile; on Ubuntu it configures the official PostgreSQL apt repository and installs the same server versions. ```sh scripts/setup-host ``` -------------------------------- ### Quick Start with Logger Source: https://github.com/heroiclabs/nakama/blob/master/vendor/go.uber.org/zap/README.md Use the Logger when performance and type safety are critical. It is even faster than the SugaredLogger and allocates far less, but only supports structured logging. The example shows creating a production logger and logging with strongly typed Field values. ```go logger, _ := zap.NewProduction() defer logger.Sync() logger.Info("failed to fetch URL", // Structured context as strongly typed Field values. zap.String("url", url), zap.Int("attempt", 3), zap.Duration("backoff", time.Second), ) ``` -------------------------------- ### Complete example of RoaringBitmap usage in Go Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/RoaringBitmap/roaring/README.md Simplified but complete example demonstrating bitmap creation, cardinality, containment, set operations (And, Or), parallel operations (ParOr, ParAnd), iteration, and serialization. It omits error handling for WriteTo and ReadFrom. ```go package main import ( "fmt" "github.com/RoaringBitmap/roaring" "bytes" ) func main() { // example inspired by https://github.com/fzandona/goroar fmt.Println("==roaring==") rb1 := roaring.BitmapOf(1, 2, 3, 4, 5, 100, 1000) fmt.Println(rb1.String()) rb2 := roaring.BitmapOf(3, 4, 1000) fmt.Println(rb2.String()) rb3 := roaring.New() fmt.Println(rb3.String()) fmt.Println("Cardinality: ", rb1.GetCardinality()) fmt.Println("Contains 3? ", rb1.Contains(3)) rb1.And(rb2) rb3.Add(1) rb3.Add(5) rb3.Or(rb1) // computes union of the three bitmaps in parallel using 4 workers roaring.ParOr(4, rb1, rb2, rb3) // computes intersection of the three bitmaps in parallel using 4 workers roaring.ParAnd(4, rb1, rb2, rb3) // prints 1, 3, 4, 5, 1000 i := rb3.Iterator() for i.HasNext() { fmt.Println(i.Next()) } fmt.Println() // next we include an example of serialization buf := new(bytes.Buffer) rb1.WriteTo(buf) // we omit error handling newrb:= roaring.New() newrb.ReadFrom(buf) if rb1.Equals(newrb) { fmt.Println("I wrote the content to a byte stream and read it back.") } // you can iterate over bitmaps using ReverseIterator(), Iterator, ManyIterator() } ``` -------------------------------- ### Set up full development environment with mise Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md Sets up the full development environment using mise and runs the entire test suite. Requires the maintained setup described in DEVELOPMENT.md. ```bash mise install mise run dev:init mise run dev ./test.sh all ``` -------------------------------- ### Install code generation toolchain Source: https://github.com/heroiclabs/nakama/blob/master/README.md Installs the Go tools required to generate protocol buffers and gateway code. ```shell go install \ "google.golang.org/protobuf/cmd/protoc-gen-go" \ "google.golang.org/grpc/cmd/protoc-gen-go-grpc" \ "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway" \ "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2" ``` -------------------------------- ### Usage example with atomic.Uint32 Source: https://github.com/heroiclabs/nakama/blob/master/vendor/go.uber.org/atomic/README.md Demonstrates the basic usage of the atomic package. It creates an atomic.Uint32, stores a value, subtracts, and performs a compare-and-swap operation. ```go var atom atomic.Uint32 atom.Store(42) atom.Sub(2) atom.CAS(40, 11) ``` -------------------------------- ### Install pgx v5 Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/jackc/pgx/v5/README.md Installs the pgx v5 module using the Go module tool. ```bash go get github.com/jackc/pgx/v5 ``` -------------------------------- ### Install GopherLua with go get Source: https://github.com/heroiclabs/nakama/blob/master/internal/gopher-lua/README.rst Install the GopherLua package using the Go module tool. Requires Go 1.9 or later. ```bash go get github.com/yuin/gopher-lua ``` -------------------------------- ### Install t-digest with go get Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/caio/go-tdigest/README.md Install the t-digest library. The first command fetches the latest version from the default branch, while the second uses a versioned import path to avoid breaking changes. ```bash go get github.com/caio/go-tdigest ``` ```bash go get gopkg.in/caio/go-tdigest.v2 ``` -------------------------------- ### Get/Create a metric, use it Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/uber-go/tally/v4/README.md Shows how to get a counter and a gauge from a scope and update them. The comments suggest caching the metric handles. ```go // Get a counter, increment a counter reqCounter := scope.Counter("requests") // cache me reqCounter.Inc(1) queueGauge := scope.Gauge("queue_length") // cache me queueGauge.Update(42) ``` -------------------------------- ### Install jwt-go dependency with go get Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/golang-jwt/jwt/v5/README.md Adds golang-jwt/jwt/v5 as a Go dependency. Requires Go to be installed. ```sh go get -u github.com/golang-jwt/jwt/v5 ``` -------------------------------- ### Run JavaScript and get result value Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/dop251/goja/README.md Basic example of creating a goja runtime, running a JavaScript string, and exporting the result to a Go int64. ```go vm := goja.New() v, err := vm.RunString("2 + 2") if err != nil { panic(err) } if num := v.Export().(int64); num != 4 { panic(num) } ``` -------------------------------- ### Rotate on SIGHUP example Source: https://github.com/heroiclabs/nakama/blob/master/vendor/gopkg.in/natefinch/lumberjack.v2/README.md Example of rotating the log file in response to SIGHUP. Sets the logger as the output for the standard log package and starts a goroutine that calls Rotate on each SIGHUP signal. ```go l := &lumberjack.Logger{} log.SetOutput(l) c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGHUP) go func() { for { <-c l.Rotate() } }() ``` -------------------------------- ### Example Usage: Creating a Puddle Pool and Acquiring a Resource Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/jackc/puddle/v2/README.md Shows how to create a puddle pool with a constructor and destructor, acquire a resource, use it, and release it. The constructor dials a TCP connection, and the destructor closes it. The pool size is set to 10. This example demonstrates the core API: puddle.NewPool, pool.Acquire, res.Value, and res.Release. ```go package main import ( "context" "log" "net" "github.com/jackc/puddle/v2" ) func main() { constructor := func(context.Context) (net.Conn, error) { return net.Dial("tcp", "127.0.0.1:8080") } destructor := func(value net.Conn) { value.Close() } maxPoolSize := int32(10) pool, err := puddle.NewPool(&puddle.Config[net.Conn]{Constructor: constructor, Destructor: destructor, MaxSize: maxPoolSize}) if err != nil { log.Fatal(err) } // Acquire resource from the pool. res, err := pool.Acquire(context.Background()) if err != nil { log.Fatal(err) } // Use resource. _, err = res.Value().Write([]byte{1}) if err != nil { log.Fatal(err) } // Release when done. res.Release() } ``` -------------------------------- ### 64-bit Roaring example in Go Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/RoaringBitmap/roaring/README.md Example using the roaring64 package for 64-bit integers. Demonstrates bitmap creation, operations, iteration, and serialization, similar to the 32-bit version. Note that 64-bit format is not guaranteed to be cross-operable. ```go package main import ( "fmt" "github.com/RoaringBitmap/roaring/roaring64" "bytes" ) func main() { // example inspired by https://github.com/fzandona/goroar fmt.Println("==roaring64==") rb1 := roaring64.BitmapOf(1, 2, 3, 4, 5, 100, 1000) fmt.Println(rb1.String()) rb2 := roaring64.BitmapOf(3, 4, 1000) fmt.Println(rb2.String()) rb3 := roaring64.New() fmt.Println(rb3.String()) fmt.Println("Cardinality: ", rb1.GetCardinality()) fmt.Println("Contains 3? ", rb1.Contains(3)) rb1.And(rb2) rb3.Add(1) rb3.Add(5) rb3.Or(rb1) // prints 1, 3, 4, 5, 1000 i := rb3.Iterator() for i.HasNext() { fmt.Println(i.Next()) } fmt.Println() // next we include an example of serialization buf := new(bytes.Buffer) rb1.WriteTo(buf) // we omit error handling newrb:= roaring64.New() newrb.ReadFrom(buf) if rb1.Equals(newrb) { fmt.Println("I wrote the content to a byte stream and read it back.") } // you can iterate over bitmaps using ReverseIterator(), Iterator, ManyIterator() } ``` -------------------------------- ### Setup Go plugin project with nakama-common dependency Source: https://github.com/heroiclabs/nakama/blob/master/sample_go_module/README.md Commands to set up a Go plugin project for Nakama. First creates and enters a directory for the plugin code, then initializes a Go module and adds the nakama-common dependency. For Nakama's master branch, drop the @v1.23.0 version reference. Nakama v3.12.+ requires nakama-common v1.23.0; using a different version may cause a 'plugin was built with a different version of package' error at server startup. ```bash mkdir -p "$HOME/plugin_code" cd "$HOME/plugin_code" ``` ```bash go mod init "plugin_code" go get -u "github.com/heroiclabs/nakama-common@v1.23.0" ``` -------------------------------- ### Example use: BitSet operations and chaining Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/bits-and-blooms/bitset/README.md Complete Go program demonstrating basic BitSet operations: Set, Test, Clear, chaining, NextSet iteration, and Intersection. Uses math/rand for random card simulation. ```go package main import ( "fmt" "math/rand" "github.com/bits-and-blooms/bitset" ) func main() { fmt.Printf("Hello from BitSet!\n") var b bitset.BitSet // play some Go Fish for i := 0; i < 100; i++ { card1 := uint(rand.Intn(52)) card2 := uint(rand.Intn(52)) b.Set(card1) if b.Test(card2) { fmt.Println("Go Fish!") } b.Clear(card1) } // Chaining b.Set(10).Set(11) for i, e := b.NextSet(0); e; i, e = b.NextSet(i + 1) { fmt.Println("The following bit is set:", i) } if b.Intersection(bitset.New(100).Set(10)).Count() == 1 { fmt.Println("Intersection works.") } else { fmt.Println("Intersection doesn't work???") } } ``` -------------------------------- ### Iterative use with gore Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/RoaringBitmap/roaring/README.md Shows an interactive gore session importing the roaring package, creating a bitmap, adding a value, and printing its string representation. Requires gore and the roaring package installed via go get. ```go $ gore gore version 0.2.6 :help for help gore> :import github.com/RoaringBitmap/roaring gore> x:=roaring.New() gore> x.Add(1) gore> x.String() "{1}" ``` -------------------------------- ### Build and run a Nakama plugin with Docker Source: https://github.com/heroiclabs/nakama/blob/master/sample_go_module/README.md Use the Docker plugin builder container to compile the plugin, then start the server and database together with Docker Compose. The build command bind-mounts the current folder into the container and writes the output .so file to ./modules/plugin_code.so; copy the generated .so files to the /modules folder of the Nakama source before running docker-compose up. The server loads plugins from ./modules by default. ```bash cd "$HOME/plugin_code" # Your project folder. See instructions above. docker run --rm -w "/builder" -v "${PWD}:/builder" heroiclabs/nakama-pluginbuilder:3.12.0 build -buildmode=plugin -trimpath -o ./modules/plugin_code.so ``` ```bash docker-compose up ``` -------------------------------- ### Output of the yaml example program Source: https://github.com/heroiclabs/nakama/blob/master/vendor/go.yaml.in/yaml/v3/README.md Expected output from the example program, showing the unmarshaled struct and map, and their marshaled YAML dumps. ```text --- t: {Easy! {2 [3 4]}} --- t dump: a: Easy! b: c: 2 d: [3, 4] --- m: map[a:Easy! b:map[c:2 d:[3 4]]] --- m dump: a: Easy! b: c: 2 d: - 3 - 4 ``` -------------------------------- ### Connect and query with pgconn.Connect and ExecParams Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/jackc/pgx/v5/pgconn/README.md Shows how to connect to PostgreSQL using pgconn.Connect with a DATABASE_URL environment variable, execute a parameterized query with ExecParams, iterate over result rows, and close the connection. The example logs fatal errors on connection or result reading failures. ```go pgConn, err := pgconn.Connect(context.Background(), os.Getenv("DATABASE_URL")) if err != nil { log.Fatalln("pgconn failed to connect:", err) } defer pgConn.Close(context.Background()) result := pgConn.ExecParams(context.Background(), "SELECT email FROM users WHERE id=$1", [][]byte{[]byte("123")}, nil, nil, nil) for result.NextRow() { fmt.Println("User 123 has email:", string(result.Values()[0])) } _, err = result.Close() if err != nil { log.Fatalln("failed reading result:", err) } ``` -------------------------------- ### Working with coroutines: Resume and yield break Source: https://github.com/heroiclabs/nakama/blob/master/internal/gopher-lua/README.rst Demonstrates how to create a new thread, get a coroutine function from Lua, and resume it in a loop, handling errors and normal completion. ```go co, _ := L.NewThread() /* create a new thread */ fn := L.GetGlobal("coro").(*lua.LFunction) /* get function from lua */ for { st, err, values := L.Resume(co, fn) if st == lua.ResumeError { fmt.Println("yield break(error)") fmt.Println(err.Error()) break } for i, lv := range values { fmt.Printf("%v : %v\n", i, lv) } if st == lua.ResumeOK { fmt.Println("yield break(ok)") break } } ``` -------------------------------- ### Using intmap with int64 keys and values Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/kamstrup/intmap/README.md Basic usage of the intmap package: create a map with initial capacity, put, get, delete, iterate, and clear. The Get method returns a value and a boolean indicating presence. Clear removes all entries but retains the underlying buffers. ```go m := intmap.New[int64,int64](32768) m.Put(int64(1234), int64(-222)) m.Put(int64(123), int64(33)) v, ok := m.Get(int64(222)) v, ok := m.Get(int64(333)) m.Del(int64(222)) m.Del(int64(333)) fmt.Println(m.Len()) m.ForEach(func(k int64, v int64) { fmt.Printf("key: %d, value: %d\n", k, v) }) m.Clear() // all gone, but buffers kept ``` -------------------------------- ### Build and test commands for pgx Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/jackc/pgx/v5/CLAUDE.md Commands for building, testing, formatting, and managing database targets in the pgx repository. Use `mise run dev` to start PostgreSQL 18 and the supervisor; tests start other targets on demand. `./test.sh` runs the full suite against PostgreSQL 18 by default, with options for specific targets and passing arguments to `go test`. Always run `goimports -w .` after changes and `golangci-lint run ./...` for linting. ```bash mise run dev # start PostgreSQL 18 and the database supervisor mise run dev:all # eagerly start every available database mise run dev -- -D # ... detached; then `mise run dev:wait`, and # `mise run dev:down` when finished. Agents must do this. ./test.sh # Full suite against PostgreSQL 18 (the default target) ./test.sh pg16 # Against PostgreSQL 16 ./test.sh crdb # Against CockroachDB ./test.sh all # Every target (pg14-18 + crdb) ./test.sh pg16 -run TestConnect # Trailing arguments are passed to `go test` go test ./... # Also works: mise loads the default target's PGX_TEST_* go test -race ./... # With the race detector goimports -w . # Format (always run after making changes) golangci-lint run ./... # Lint mise run dev:ports # This checkout's ports and where each server's data lives mise run db:start pg16 crdb # Prewarm targets; tests then leave them running mise run db:stop pg16 crdb # Stop prewarmed targets mise run db:psql # psql against PostgreSQL 18; `mise run db:psql 16` for another process-compose process logs pg16 # One server's output ``` -------------------------------- ### Run tests with Docker Compose and Go test Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/heroiclabs/sql-migrate/README.md Starts the Postgres Docker container and runs the test suite. Execute these commands in the project root after ensuring Docker is available. ```bash docker compose up go test ``` -------------------------------- ### Route matching order: first match wins Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/gorilla/mux/README.md Routes are tested in the order they were added. If two routes match, the first one wins. This example shows a specific route before a catch-all prefix. ```go r := mux.NewRouter() r.HandleFunc("/specific", specificHandler) r.PathPrefix("/").Handler(catchAllHandler) ``` -------------------------------- ### Create Docker builder context Source: https://github.com/heroiclabs/nakama/blob/master/build/README.md Creates a new Docker context for multi-platform builds. One-off setup step. ```bash docker context create builder ``` -------------------------------- ### Manage local database servers with process-compose and mise Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/jackc/pgx/v5/DEVELOPMENT.md Commands for managing the local database servers started by `mise run dev`. `process-compose` commands need no flags because `PC_PORT_NUM` is set in this checkout's environment. `mise run db:start` prewarms one or more targets (e.g., `pg16`, `crdb`, or `all`), and `mise run db:psql` connects to the already-running PostgreSQL 18 by default; passing a major version (e.g., `16`) selects that server, and arguments after the major are passed to psql. ```sh process-compose process list # status, scriptable process-compose process logs pg16 # one server's output mise run db:start pg16 crdb # prewarm one or more targets mise run db:stop pg16 crdb # stop them again mise run db:start all # prewarm every target process-compose down # stop this checkout's stack only mise run db:psql # psql against the already-running PostgreSQL 18 mise run db:start pg16 # prewarm PostgreSQL 16 before interactive use mise run db:psql 16 # psql against PostgreSQL 16 mise run db:psql 16 -c 'select 1' # arguments after the major go to psql ``` -------------------------------- ### Add or update a dependency with go get Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/prometheus/procfs/CONTRIBUTING.md Use the go get command to add or update a dependency. The first command fetches the latest tagged release, while the second fetches a specific version using the @vX.Y.Z suffix. ```bash # Pick the latest tagged release. go get example.com/some/module/pkg # Pick a specific version. go get example.com/some/module/pkg@vX.Y.Z ``` -------------------------------- ### Parse and query a source map (ExampleParse) Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/go-sourcemap/sourcemap/README.md Shows how to fetch a source map, parse it with sourcemap.Parse, and use smap.Source to map a line and column to the original source. The example expects the output: http://code.jquery.com/jquery-2.0.3.js apply 4360 27 true. ```go func ExampleParse() { mapURL := "http://code.jquery.com/jquery-2.0.3.min.map" resp, err := http.Get(mapURL) if err != nil { panic(err) } defer resp.Body.Close() b, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } smap, err := sourcemap.Parse(mapURL, b) if err != nil { panic(err) } line, column := 5, 6789 file, fn, line, col, ok := smap.Source(line, column) fmt.Println(file, fn, line, col, ok) // Output: http://code.jquery.com/jquery-2.0.3.js apply 4360 27 true } ``` -------------------------------- ### Initialize blockdevice with proc and sys filesystems Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/prometheus/procfs/README.md Shows how to use the blockdevice sub-package, which requires access to both /proc and /sys, to read disk statistics. ```go fs, err := blockdevice.NewFS("/proc", "/sys") stats, err := fs.ProcDiskstats() ``` -------------------------------- ### Register routes in a subrouter Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/gorilla/mux/README.md Registers three routes on the subrouter created in the previous example. These routes are only tested if the domain is www.example.com. ```go s.HandleFunc("/products/", ProductsHandler) s.HandleFunc("/products/{key}", ProductHandler) s.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) ``` -------------------------------- ### Create and setup pgx test database Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md Creates and initializes a test database named pgx_test, including required extensions and a custom domain. Use this when you have an existing PostgreSQL development server. ```bash export PGDATABASE=pgx_test createdb psql -c 'create extension hstore;' psql -c 'create extension ltree;' psql -c 'create domain uint64 as numeric(20,0);' ``` -------------------------------- ### Fuzzy testing setup and run Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/RoaringBitmap/roaring/README.md Commands to set up and run fuzzy testing on the roaring library. After running, check the workdir for crash reports if the number of crashers is greater than zero. The -func flag can be replaced with FuzzSerializationBuffer or FuzzSerializationStream. ```bash go get github.com/dvyukov/go-fuzz/go-fuzz go get github.com/dvyukov/go-fuzz/go-fuzz-build go test -tags=gofuzz -run=TestGenerateSmatCorpus go-fuzz-build github.com/RoaringBitmap/roaring go-fuzz -bin=./roaring-fuzz.zip -workdir=workdir/ -timeout=200 -func FuzzSmat ``` -------------------------------- ### Run database migration Source: https://github.com/heroiclabs/nakama/blob/master/README.md Executes the database migration to set up or upgrade the schema. Must be run before starting the server. Connects to CockroachDB at the specified address. ```shell nakama migrate --database.address "root@127.0.0.1:26257" ``` -------------------------------- ### Go usage example for skiplist Source: https://github.com/heroiclabs/nakama/blob/master/internal/skiplist/README.md Demonstrates creating a skip list, inserting User elements, traversing in order, and using GetRank and GetElementByRank. The output shows the sorted order by score (descending) and then by id length for ties. ```Go package main import ( "fmt" "github.com/gansidui/skiplist" "log" ) type User struct { score float64 id string } func (u *User) Less(other interface{}) bool { if u.score > other.(*User).score { return true } if u.score == other.(*User).score && len(u.id) > len(other.(*User).id) { return true } return false } func main() { us := make([]*User, 7) us[0] = &User{6.6, "hi"} us[1] = &User{4.4, "hello"} us[2] = &User{2.2, "world"} us[3] = &User{3.3, "go"} us[4] = &User{1.1, "skip"} us[5] = &User{2.2, "list"} us[6] = &User{3.3, "lang"} // insert sl := skiplist.New() for i := 0; i < len(us); i++ { sl.Insert(us[i]) } // traverse for e := sl.Front(); e != nil; e = e.Next() { fmt.Println(e.Value.(*User).id, "-->", e.Value.(*User).score) } fmt.Println() // rank rank1 := sl.GetRank(&User{2.2, "list"}) rank2 := sl.GetRank(&User{6.6, "hi"}) if rank1 != 6 || rank2 != 1 { log.Fatal() } if e := sl.GetElementByRank(2); e.Value.(*User).score != 4.4 || e.Value.(*User).id != "hello" { log.Fatal() } } /* output: hi --> 6.6 hello --> 4.4 lang --> 3.3 go --> 3.3 world --> 2.2 list --> 2.2 skip --> 1.1 */ ``` -------------------------------- ### Clone and run the demo Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/axiomhq/hyperloglog/Contributing.md Clone the repository, change into the demo directory, and run the hyperloglog demo with Go. ```bash git clone https://github.com/axiomhq/hyperloglog.git cd hyperloglog cd demo go run hyperloglog_demo.go ``` -------------------------------- ### Build only host or path with URLHost() and URLPath() Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/gorilla/mux/README.md Builds only the host or path for a named route using URLHost() and URLPath(). The examples show the resulting strings for the given variables. ```go // "http://news.example.com/" host, err := r.Get("article").URLHost("subdomain", "news") // "/articles/technology/42" path, err := r.Get("article").URLPath("category", "technology", "id", "42") ``` -------------------------------- ### Pull xgo Docker image Source: https://github.com/heroiclabs/nakama/blob/master/build/README.md Installs the xgo Docker image required for cross-compiling Nakama releases. Requires Docker engine. ```bash docker pull techknowlogick/xgo:latest ``` -------------------------------- ### Serve SPA with custom handler and API routes Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/gorilla/mux/README.md Complete example of serving a single page application (SPA) with a custom spaHandler that falls back to index.html for non-file paths. Also includes an API health endpoint and server timeouts. ```go package main import ( "encoding/json" "log" "net/http" "os" "path/filepath" "time" "github.com/gorilla/mux" ) // spaHandler implements the http.Handler interface, so we can use it // to respond to HTTP requests. The path to the static directory and // path to the index file within that static directory are used to // serve the SPA in the given static directory. type spaHandler struct { staticPath string indexPath string } // ServeHTTP inspects the URL path to locate a file within the static dir // on the SPA handler. If a file is found, it will be served. If not, the // file located at the index path on the SPA handler will be served. This // is suitable behavior for serving an SPA (single page application). func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Join internally call path.Clean to prevent directory traversal path := filepath.Join(h.staticPath, r.URL.Path) // check whether a file exists or is a directory at the given path fi, err := os.Stat(path) if os.IsNotExist(err) || fi.IsDir() { // file does not exist or path is a directory, serve index.html http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath)) return } if err != nil { // if we got an error (that wasn't that the file doesn't exist) stating the // file, return a 500 internal server error and stop http.Error(w, err.Error(), http.StatusInternalServerError) return } // otherwise, use http.FileServer to serve the static file http.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r) } func main() { router := mux.NewRouter() router.HandleFunc("/api/health", func(w http.ResponseWriter, r *http.Request) { // an example API handler json.NewEncoder(w).Encode(map[string]bool{"ok": true}) }) spa := spaHandler{staticPath: "build", indexPath: "index.html"} router.PathPrefix("/").Handler(spa) srv := &http.Server{ Handler: router, Addr: "127.0.0.1:8000", // Good practice: enforce timeouts for servers you create! WriteTimeout: 15 * time.Second, ReadTimeout: 15 * time.Second, } log.Fatal(srv.ListenAndServe()) } ``` -------------------------------- ### Build URL with subrouter host and path Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/gorilla/mux/README.md Defines a subrouter with a host and a path, then builds a full URL using the parent router's Get method. The result is "http://news.example.com/articles/technology/42". ```go r := mux.NewRouter() s := r.Host("{subdomain}.example.com").Subrouter() s.Path("/articles/{category}/{id:[0-9]+}"). HandlerFunc(ArticleHandler). Name("article") // "http://news.example.com/articles/technology/42" url, err := r.Get("article").URL("subdomain", "news", "category", "technology", "id", "42") ``` -------------------------------- ### Walk all registered routes Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/gorilla/mux/README.md Uses the Walk function to iterate over all routes on a router, printing path templates, regexps, query templates, query regexps, and methods for each route. The example includes a full main program. ```go package main import ( "fmt" "net/http" "strings" "github.com/gorilla/mux" ) func handler(w http.ResponseWriter, r *http.Request) { return } func main() { r := mux.NewRouter() r.HandleFunc("/", handler) r.HandleFunc("/products", handler).Methods("POST") r.HandleFunc("/articles", handler).Methods("GET") r.HandleFunc("/articles/{id}", handler).Methods("GET", "PUT") r.HandleFunc("/authors", handler).Queries("surname", "{surname}") err := r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error { pathTemplate, err := route.GetPathTemplate() if err == nil { fmt.Println("ROUTE:", pathTemplate) } pathRegexp, err := route.GetPathRegexp() if err == nil { fmt.Println("Path regexp:", pathRegexp) } queriesTemplates, err := route.GetQueriesTemplates() if err == nil { fmt.Println("Queries templates:", strings.Join(queriesTemplates, ",")) } queriesRegexps, err := route.GetQueriesRegexp() if err == nil { fmt.Println("Queries regexps:", strings.Join(queriesRegexps, ",")) } methods, err := route.GetMethods() if err == nil { fmt.Println("Methods:", strings.Join(methods, ",")) } fmt.Println() return nil }) if err != nil { fmt.Println(err) } http.Handle("/", r) } ``` -------------------------------- ### Example usage of t-digest Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/caio/go-tdigest/README.md Basic usage of the t-digest library: create a digest with default compression (100), add 10,000 random values, and print the median and its CDF. ```go package main import ( "fmt" "math/rand" "github.com/caio/go-tdigest" ) func main() { // Analogue to tdigest.New(tdigest.Compression(100)) t, _ := tdigest.New() for i := 0; i < 10000; i++ { // Analogue to t.AddWeighted(rand.Float64(), 1) t.Add(rand.Float64()) } fmt.Printf("p(.5) = %.6f\n", t.Quantile(0.5)) fmt.Printf("CDF(Quantile(.5)) = %.6f\n", t.CDF(t.Quantile(0.5))) } ``` -------------------------------- ### Initialize procfs and read CPU statistics Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/prometheus/procfs/README.md Shows how to initialize the proc filesystem mount point and read stat information using the root procfs package. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Create and parse UUIDs with gofrs/uuid Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/gofrs/uuid/v5/README.md Shows how to create a Version 4 UUID using uuid.NewV4() and parse a UUID from a string using uuid.FromString(). The example includes a package-level variable initialized with uuid.Must(uuid.NewV4()) that panics on error, and demonstrates error handling in the main function. ```go package main import ( "log" "github.com/gofrs/uuid/v5" ) // Create a Version 4 UUID, panicking on error. // Use this form to initialize package-level variables. var u1 = uuid.Must(uuid.NewV4()) func main() { // Create a Version 4 UUID. u2, err := uuid.NewV4() if err != nil { log.Fatalf("failed to generate UUID: %v", err) } log.Printf("generated Version 4 UUID %v", u2) // Parse a UUID from a string. s := "6ba7b810-9dad-11d1-80b4-00c04fd430c8" u3, err := uuid.FromString(s) if err != nil { log.Fatalf("failed to parse UUID %q: %v", s, err) } log.Printf("successfully parsed UUID %v", u3) } ``` -------------------------------- ### Serialization with error handling in Go Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/RoaringBitmap/roaring/README.md Example showing how to handle errors when writing and reading a Roaring bitmap to a byte buffer. Uses BitmapOf, WriteTo, ReadFrom, and Equals, with error checks using t.Errorf. ```go rb := BitmapOf(1, 2, 3, 4, 5, 100, 1000) buf := new(bytes.Buffer) size,err:=rb.WriteTo(buf) if err != nil { t.Errorf("Failed writing") } newrb:= New() size,err=newrb.ReadFrom(buf) if err != nil { t.Errorf("Failed reading") } if ! rb.Equals(newrb) { t.Errorf("Cannot retrieve serialized version") } ``` -------------------------------- ### Get variable names with GetVarNames() Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/gorilla/mux/README.md Retrieves all required variable names for a route using GetVarNames(). The example prints [domain group item_id some_data1 some_data2] <nil>. ```go r := mux.NewRouter() r.Host("{domain}"). Path("/{group}/{item_id}"). Queries("some_data1", "{some_data1}"). Queries("some_data2", "{some_data2}"). Name("article") // Will print [domain group item_id some_data1 some_data2] <nil> fmt.Println(r.Get("article").GetVarNames()) ``` -------------------------------- ### Build Nakama from source Source: https://github.com/heroiclabs/nakama/blob/master/README.md Builds the project from source and prints the version. ```shell go build -trimpath -mod=vendor ./nakama --version ``` -------------------------------- ### Get next execution time with MustParse and Next Source: https://github.com/heroiclabs/nakama/blob/master/internal/cronexpr/README.md Parse a cron expression and get the next execution time after a given time. ```go nextTime := cronexpr.MustParse("0 0 29 2 *").Next(time.Now()) ``` -------------------------------- ### Build the codebase Source: https://github.com/heroiclabs/nakama/blob/master/README.md Builds the project from source. ```shell go build -trimpath -mod=vendor ```