### Install sql-migrate Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/heroiclabs/sql-migrate/README.md Use 'go get' to install the sql-migrate package. ```bash go get -v github.com/heroiclabs/nakama/sql-migrate/ ``` -------------------------------- ### Install go.yaml.in/yaml/v3 Source: https://github.com/heroiclabs/nakama/blob/master/vendor/go.yaml.in/yaml/v3/README.md Use 'go get' to install the package. The import path is go.yaml.in/yaml/v3. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Full Example of a Mux-based Server Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/gorilla/mux/README.md Provides a complete, runnable Go program demonstrating a basic server using the Gorilla Mux router. It sets up a single route and starts the HTTP listener. ```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)) } ``` -------------------------------- ### Install cronexpr Library Source: https://github.com/heroiclabs/nakama/blob/master/internal/cronexpr/README.md Use 'go get' to install the cronexpr library. This is the first step before importing and using it in your Go projects. ```bash go get github.com/gorhill/cronexpr ``` -------------------------------- ### Install Protocol Buffer and gRPC Tools Source: https://github.com/heroiclabs/nakama/blob/master/README.md Install the necessary Protocol Buffers, gRPC, and gRPC-Gateway tools required for generating project sources. Ensure Go is installed and configured. ```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" ``` -------------------------------- ### BitSet Installation Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/bits-and-blooms/bitset/README.md Standard Go command to install the bitset library using go get. ```bash go get github.com/bits-and-blooms/bitset ``` -------------------------------- ### Install Protobuf and gRPC Plugins Source: https://context7.com/heroiclabs/nakama/llms.txt Installs necessary Go plugins for regenerating protobuf and OpenAPI files. Ensure Go is installed and configured in your PATH. ```bash go install google.golang.org/protobuf/cmd/protoc-gen-go@latest go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway@latest go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2@latest ``` -------------------------------- ### Install sourcemap Package Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/go-sourcemap/sourcemap/README.md Use 'go get' to install the sourcemap package. This command fetches and installs the latest version of the package. ```shell go get -u github.com/go-sourcemap/sourcemap ``` -------------------------------- ### Install Cronexpr Utility Source: https://github.com/heroiclabs/nakama/blob/master/internal/cronexpr/cronexpr/README.md Install the cronexpr command-line utility using go get and go install. ```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 Start the Nakama server and connect it to the database. Configuration details are available in the documentation. ```shell nakama --database.address "root@127.0.0.1:26257" ``` -------------------------------- ### Install multierr Source: https://github.com/heroiclabs/nakama/blob/master/vendor/go.uber.org/multierr/README.md Use go get to install the latest version of the multierr package. ```bash go get -u go.uber.org/multierr@latest ``` -------------------------------- ### Install Gorilla Mux Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/gorilla/mux/README.md Install the gorilla/mux package using the go get command. Ensure your Go toolchain is correctly configured. ```sh go get -u github.com/gorilla/mux ``` -------------------------------- ### Setup Test Database in New Cluster Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md Commands to create the test database and populate it with necessary schemas and data by running a SQL script. This is done after starting the new PostgreSQL cluster. ```bash createdb psql --no-psqlrc -f testsetup/postgresql_setup.sql ``` -------------------------------- ### Install yaml.v3 Go Package Source: https://github.com/heroiclabs/nakama/blob/master/vendor/gopkg.in/yaml.v3/README.md Use 'go get' to install the yaml.v3 package for use in your Go projects. ```bash go get gopkg.in/yaml.v3 ``` -------------------------------- ### Install xgo Command Line Tool Source: https://github.com/heroiclabs/nakama/blob/master/build/README.md Installs the xgo command line helper tool. Ensure that $GOPATH/bin is in your system's PATH to access the executable. ```bash go install src.techknowlogick.com/xgo@latest ``` -------------------------------- ### Fuzzy Testing Setup Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/RoaringBitmap/roaring/README.md Instructions for setting up and running fuzzy tests to find bugs in the library. This involves installing fuzzing tools and running specific test commands. ```sh 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 ``` -------------------------------- ### Statsd Reporter Setup Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/uber-go/tally/v4/README.md Example of setting up a statsd reporter with Tally. Ensure the statsd client is correctly configured with address and prefix. ```go import ( "io" "github.com/cactus/go-statsd-client/v5/statsd" "github.com/uber-go/tally" tallystatsd "github.com/uber-go/tally/statsd" // ... ) func newScope() (tally.Scope, io.Closer) { statter, _ := statsd.NewBufferedClient("127.0.0.1:8125", "stats", 100*time.Millisecond, 1440) reporter := tallystatsd.NewReporter(statter, tallystatsd.Options{ SampleRate: 1.0, }) scope, closer := tally.NewRootScope(tally.ScopeOptions{ Prefix: "my-service", Tags: map[string]string{}, Reporter: reporter, }, time.Second) return scope, closer } ``` -------------------------------- ### Install Roaring Bitmaps Go Library Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/RoaringBitmap/roaring/README.md Use 'go get -t' to fetch the Roaring Bitmaps library and its dependencies. ```bash go get -t github.com/RoaringBitmap/roaring ``` -------------------------------- ### Install Compute Metadata Library Source: https://github.com/heroiclabs/nakama/blob/master/vendor/cloud.google.com/go/compute/metadata/README.md Use this command to install the Go utility library for communicating with the Google Cloud metadata service. ```bash go get cloud.google.com/go/compute/metadata ``` -------------------------------- ### Install Uber Go Atomic Source: https://github.com/heroiclabs/nakama/blob/master/vendor/go.uber.org/atomic/README.md Use 'go get' to install the latest version of the atomic package. ```shell $ go get -u go.uber.org/atomic@v1 ``` -------------------------------- ### Install go-fuzz Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/blevesearch/segment/README.md Install the go-fuzz tool and go-fuzz-build for fuzz testing the segment library. ```bash go get github.com/dvyukov/go-fuzz/go-fuzz go get github.com/dvyukov/go-fuzz/go-fuzz-build ``` -------------------------------- ### Install GopherLua Source: https://github.com/heroiclabs/nakama/blob/master/internal/gopher-lua/README.rst Install the GopherLua package using go get. Requires Go 1.9 or later. ```bash go get github.com/yuin/gopher-lua ``` -------------------------------- ### Logging and Compression Handler Example Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/gorilla/handlers/README.md Demonstrates how to use LoggingHandler for request logging and CompressHandler for gzipping responses. Ensure the correct imports are present. ```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 GopherLua Standalone Interpreter Source: https://github.com/heroiclabs/nakama/blob/master/internal/gopher-lua/README.rst Use 'go get' to install the 'glua' command-line interpreter for GopherLua. This interpreter has the same options as the standard Lua interpreter. ```bash go get github.com/yuin/gopher-lua/cmd/glua ``` -------------------------------- ### Initialize Procfs and Get Stats Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/prometheus/procfs/README.md Initializes the proc filesystem and retrieves CPU statistics. Use this to get basic system-wide CPU metrics. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Minimal Go Module Initialization Source: https://github.com/heroiclabs/nakama/blob/master/sample_go_module/README.md This is the smallest example of a Go module for the Nakama server runtime. It demonstrates the required InitModule function signature. ```go package main import ( "context" "database/sql" "github.com/heroiclabs/nakama-common/runtime" ) func InitModule(ctx context.Context, logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule, initializer runtime.Initializer) error { logger.Info("module loaded") return nil } ``` -------------------------------- ### Setup Zap Repository Source: https://github.com/heroiclabs/nakama/blob/master/vendor/go.uber.org/zap/CONTRIBUTING.md Clone the zap repository and set up the upstream remote for contributing. ```bash mkdir -p $GOPATH/src/go.uber.org cd $GOPATH/src/go.uber.org git clone git@github.com:your_github_username/zap.git cd zap git remote add upstream https://github.com/uber-go/zap.git git fetch upstream ``` -------------------------------- ### Build Nakama from Source Source: https://github.com/heroiclabs/nakama/blob/master/README.md Build the Nakama project from source using Go. Ensure you have the Go toolchain installed and dependencies are vendored. ```shell go build -trimpath -mod=vendor ./nakama --version ``` -------------------------------- ### Example Output of Snowball Stemming Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/blevesearch/snowballstem/README.md Shows the expected output when running the Go code example for stemming words. ```bash $ ./snowtest running stemmed to run jumping stemmed to jump ``` -------------------------------- ### Install gRPC-Go Source: https://github.com/heroiclabs/nakama/blob/master/vendor/google.golang.org/grpc/README.md Add this import to your Go code to automatically fetch gRPC-Go dependencies during build, run, or test. ```go import "google.golang.org/grpc" ``` -------------------------------- ### Start PostgreSQL Cluster Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md Command to start the PostgreSQL server using the configured data directory. This must be run before executing pgx tests that require a running database. ```bash postgres -D .testdb/$POSTGRESQL_DATA_DIR ``` -------------------------------- ### Run Tests with Docker Compose Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/heroiclabs/sql-migrate/README.md Execute tests by first starting the PostgreSQL Docker container and then running the Go tests. ```bash docker compose up go test ``` -------------------------------- ### Install xgo Docker Image Source: https://github.com/heroiclabs/nakama/blob/master/build/README.md Pulls the latest xgo Docker image, which is used for cross-compiling Nakama server builds. ```bash docker pull techknowlogick/xgo:latest ``` -------------------------------- ### Setup and Run Hyperloglog Demo Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/axiomhq/hyperloglog/Contributing.md Follow these steps to set up your development environment by forking and cloning the repository, navigating to the demo directory, and running the demonstration program. ```bash git clone https://github.com/axiomhq/hyperloglog.git cd hyperloglog cd demo go run hyperloglog_demo.go ``` -------------------------------- ### GopherLua Channel Communication Example Source: https://github.com/heroiclabs/nakama/blob/master/internal/gopher-lua/README.rst Demonstrates sending and receiving data between Go and Lua using channels, including select with handlers and closing channels. ```go func receiver(ch, quit chan lua.LValue) { L := lua.NewState() defer L.Close() L.SetGlobal("ch", lua.LChannel(ch)) L.SetGlobal("quit", lua.LChannel(quit)) if err := L.DoString(` local exit = false while not exit do channel.select( {"|<-", ch, function(ok, v) if not ok then print("channel closed") exit = true else print("received:", v) end end}, {"|<-", quit, function(ok, v) print("quit") exit = true end} ) end `); err != nil { panic(err) } } ``` ```go func sender(ch, quit chan lua.LValue) { L := lua.NewState() defer L.Close() L.SetGlobal("ch", lua.LChannel(ch)) L.SetGlobal("quit", lua.LChannel(quit)) if err := L.DoString(` ch:send("1") ch:send("2") `); err != nil { panic(err) } ch <- lua.LString("3") quit <- lua.LTrue } ``` ```go func main() { ch := make(chan lua.LValue) quit := make(chan lua.LValue) go receiver(ch, quit) go sender(ch, quit) time.Sleep(3 * time.Second) } ``` -------------------------------- ### Converting Between BitSet and Roaring Bitmaps Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/bits-and-blooms/bitset/README.md Provides examples of converting between conventional bitset instances and compressed Roaring bitmaps using provided utility functions. ```go mybitset := roaringbitmap.ToBitSet() newroaringbitmap := roaring.FromBitSet(mybitset) ``` -------------------------------- ### Add or Update Dependency Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/prometheus/procfs/CONTRIBUTING.md Use 'go get' to add or update external packages. Remember to commit the updated go.mod, go.sum, and vendor directory. ```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 ``` -------------------------------- ### Setup Test Database and Extensions Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md Commands to set up a test database, create necessary extensions like hstore and ltree, and define a custom domain for use with pgx tests. ```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);' ``` -------------------------------- ### Build Nakama Server from Source Source: https://context7.com/heroiclabs/nakama/llms.txt Clone the Nakama repository, build the binary using Go, and run database migrations. Ensure dependencies are vendored for a consistent build. ```shell # Clone the repo git clone https://github.com/heroiclabs/nakama nakama cd nakama # Build the binary (all dependencies are vendored) go build -trimpath -mod=vendor ./nakama --version # Run database migration and start the server ./nakama migrate up --database.address "root@127.0.0.1:26257" ./nakama --database.address "root@127.0.0.1:26257" --logger.level DEBUG ``` -------------------------------- ### Basic BitSet Usage and Chaining Example Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/bits-and-blooms/bitset/README.md Demonstrates fundamental BitSet operations like setting, testing, clearing bits, and chaining methods. Also shows iteration over set bits and intersection. ```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???") } } ``` -------------------------------- ### Run Nakama Server with Custom Plugin Source: https://github.com/heroiclabs/nakama/blob/master/sample_go_module/README.md Command to start the Nakama server binary, specifying the directory containing the built plugin using the --runtime.path flag. ```bash ./nakama --runtime.path "$HOME/plugin_code" ``` -------------------------------- ### DoWhileStatement AST Node Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/dop251/goja/ast/README.markdown Represents a do-while loop in the AST. Provides methods to get the start and end indices of the node. ```go func (self *DoWhileStatement) Idx0() file.Idx ``` ```go func (self *DoWhileStatement) Idx1() file.Idx ``` -------------------------------- ### Create and Use a Resource Pool in Go Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/jackc/puddle/v2/README.md Demonstrates how to create a new resource pool with a constructor and destructor, acquire a resource, use it, and then release it back to the pool. Ensure the pool size is configured appropriately for your application's needs. ```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() } ``` -------------------------------- ### Setup Go Project for Nakama Plugin Source: https://github.com/heroiclabs/nakama/blob/master/sample_go_module/README.md Commands to initialize a Go module for a Nakama plugin and add the nakama-common dependency. Ensure you use the correct version of nakama-common for your Nakama server. ```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" ``` -------------------------------- ### Initialize and Configure PostgreSQL Data Directory Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md Commands to initialize a new PostgreSQL data directory, configure server settings like listen addresses and port, copy SSL configuration, and set up the pg_hba.conf file for authentication. ```bash initdb --locale=en_US -E UTF-8 --username=postgres .testdb/$POSTGRESQL_DATA_DIR echo "listen_addresses = '127.0.0.1'" >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf echo "port = $PGPORT" >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf cat testsetup/postgresql_ssl.conf >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf cp testsetup/pg_hba.conf .testdb/$POSTGRESQL_DATA_DIR/pg_hba.conf ``` -------------------------------- ### Gzip Stateless Compression with Bufio Writer Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/klauspost/compress/README.md Demonstrates how to use gzip with stateless compression and a 4KB bufio.Writer. This is useful for scenarios with many concurrent compressors with little activity, but may result in suboptimal compression ratios and per-write memory allocations. ```go import ( "bufio" "github.com/klauspost/compress/gzip" "io/ioutil" ) // replace 'ioutil.Discard' with your output. gzw, err := gzip.NewWriterLevel(ioutil.Discard, gzip.StatelessCompression) if err != nil { return err } defer gzw.Close() w := bufio.NewWriterSize(gzw, 4096) defer w.Flush() // Write to 'w' ``` -------------------------------- ### Start Nakama Docker Compose and Health Check Source: https://context7.com/heroiclabs/nakama/llms.txt Commands to start the Nakama environment defined in docker-compose.yml and perform a basic health check. ```shell # Start everything docker-compose up # Health check curl http://127.0.0.1:7350/healthcheck # 200 OK ``` -------------------------------- ### Basic intmap Usage in Go Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/kamstrup/intmap/README.md Demonstrates creating a new intmap, adding key-value pairs, retrieving values, deleting entries, checking the length, iterating over elements, and clearing the map. Ensure you import the 'fmt' package for printing. ```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 ``` -------------------------------- ### Connect and Execute Query with pgconn Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/jackc/pgx/v5/pgconn/README.md Demonstrates connecting to a PostgreSQL database using a connection string and executing a parameterized query. Ensure the DATABASE_URL environment variable is set. ```go pgConn, err := pgconn.Connect(context.Background(), os.Getenv("DATABASE_URL")) if err != nil { log.Fatalln("pgconn failed to connect:", err) } deffer 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) } ``` -------------------------------- ### Get Value from Lua Stack Source: https://github.com/heroiclabs/nakama/blob/master/internal/gopher-lua/README.rst Retrieve a value from the top of the Lua stack in Go using the Get method. This is part of GopherLua's data model interaction. ```go lv := L.Get(-1) // get the value at the top of the stack ``` -------------------------------- ### Rotate Logger on SIGHUP Example Source: https://github.com/heroiclabs/nakama/blob/master/vendor/gopkg.in/natefinch/lumberjack.v2/README.md Example of how to rotate logs in response to a SIGHUP signal. This involves setting up a channel to receive signals and calling the Rotate method when a SIGHUP is detected. ```go l := &lumberjack.Logger{} log.SetOutput(l) c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGHUP) gO func() { for { < -c l.Rotate() } }() ``` -------------------------------- ### Date Constructor Integer Overflow Example Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/dop251/goja/README.md Shows an example of potential incorrect results from the Date constructor when arguments cause an integer overflow, due to Go's use of `int` for epoch timestamps instead of `float` as specified by ECMAScript. ```javascript Date.UTC(1970, 0, 1, 80063993375, 29, 1, -288230376151711740) // returns 29256 instead of 29312 ``` -------------------------------- ### Idx0 Method Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/dop251/goja/ast/README.markdown Returns the starting index of the AST node. ```go func (self *ArrayLiteral) Idx0() file.Idx ``` ```go func (self *AssignExpression) Idx0() file.Idx ``` ```go func (self *BadExpression) Idx0() file.Idx ``` ```go func (self *BadStatement) Idx0() file.Idx ``` ```go func (self *BinaryExpression) Idx0() file.Idx ``` ```go func (self *BlockStatement) Idx0() file.Idx ``` ```go func (self *BooleanLiteral) Idx0() file.Idx ``` ```go func (self *BracketExpression) Idx0() file.Idx ``` ```go func (self *BranchStatement) Idx0() file.Idx ``` ```go func (self *CallExpression) Idx0() file.Idx ``` ```go func (self *CaseStatement) Idx0() file.Idx ``` ```go func (self *CatchStatement) Idx0() file.Idx ``` ```go func (self *ConditionalExpression) Idx0() file.Idx ``` ```go func (self *DebuggerStatement) Idx0() file.Idx ``` ```go func (self *DoWhileStatement) Idx0() file.Idx ``` -------------------------------- ### Get File Name Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/dop251/goja/file/README.markdown Retrieves the filename associated with the File object. ```go func (fl *File) Name() string ``` -------------------------------- ### Get File Base Offset Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/dop251/goja/file/README.markdown Retrieves the base offset of the file. ```go func (fl *File) Base() int ``` -------------------------------- ### Initialize Go Runtime Module with Nakama SDK Source: https://context7.com/heroiclabs/nakama/llms.txt The entry point for Go runtime modules, `InitModule` registers various hooks, RPCs, and handlers with the Nakama server using the provided SDK and Initializer. Ensure all necessary imports are included. ```go // sample_go_module/sample.go package main import ( "context" "database/sql" "encoding/json" "net/http" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama-common/rtapi" "github.com/heroiclabs/nakama-common/runtime" ) func InitModule(ctx context.Context, logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule, initializer runtime.Initializer) error { // Register a custom RPC callable by clients or HTTP key if err := initializer.RegisterRpc("go_echo_sample", rpcEcho); err != nil { return err } // Register a before-hook on a realtime socket message if err := initializer.RegisterBeforeRt("ChannelJoin", beforeChannelJoin); err != nil { return err } // Register an after-hook on a REST/gRPC API call if err := initializer.RegisterAfterGetAccount(afterGetAccount); err != nil { return err } // Register an authoritative match handler factory if err := initializer.RegisterMatch("my_match", func(ctx context.Context, logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule) (runtime.Match, error) { return &MyMatch{}, nil }); err != nil { return err } // Register session lifecycle events if err := initializer.RegisterEventSessionStart(onSessionStart); err != nil { return err } // Register a custom HTTP handler (path must begin with '/') if err := initializer.RegisterHttp("/my-webhook", myWebhookHandler); err != nil { return err } return nil } func rpcEcho(ctx context.Context, logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule, payload string) (string, error) { userID, _ := ctx.Value(runtime.RUNTIME_CTX_USER_ID).(string) logger.Info("Echo RPC called by user %s", userID) return payload, nil } func beforeChannelJoin(ctx context.Context, logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule, envelope *rtapi.Envelope) (*rtapi.Envelope, error) { logger.Info("Intercepted channel join for target: %v", envelope.GetChannelJoin().Target) return envelope, nil // return nil to block the operation } func afterGetAccount(ctx context.Context, logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule, in *api.Account) error { logger.Debug("User fetched their account: %v", in.User.Id) return nil } func onSessionStart(ctx context.Context, logger runtime.Logger, evt *api.Event) { logger.Info("Session started: %v", evt) } func myWebhookHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{"status":"ok"}`)) } ``` -------------------------------- ### Get a specific subscription Source: https://context7.com/heroiclabs/nakama/llms.txt Retrieves details for a specific subscription. Requires authentication. ```shell # Get a specific subscription curl -X GET "http://127.0.0.1:7350/v2/iap/subscription/com.example.monthly_plan" \ --header "Authorization: Bearer $TOKEN" ``` -------------------------------- ### Get matchmaker stats Source: https://context7.com/heroiclabs/nakama/llms.txt Retrieves statistics for the matchmaking system. Requires authentication. ```shell curl -X GET "http://127.0.0.1:7350/v2/matchmaker/stats" \ --header "Authorization: Bearer $TOKEN" ``` -------------------------------- ### Get File Source Code Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/dop251/goja/file/README.markdown Retrieves the source code content of the file. ```go func (fl *File) Source() string ``` -------------------------------- ### Run Nakama Server with Docker Compose Source: https://github.com/heroiclabs/nakama/blob/master/sample_go_module/README.md Command to start Nakama server and database containers using Docker Compose. Ensure the compiled plugin (.so files) are in the './modules' directory relative to the Docker Compose file. ```bash docker-compose up ``` -------------------------------- ### Install golang-jwt/jwt/v5 Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/golang-jwt/jwt/v5/README.md Use this command to add the jwt package as a dependency in your Go program. ```sh go get -u github.com/golang-jwt/jwt/v5 ``` -------------------------------- ### Basic T-Digest Usage Example Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/caio/go-tdigest/README.md Demonstrates how to create a new t-digest, add floating-point numbers, and calculate the 0.5 quantile and its corresponding CDF value. Uses default compression settings. ```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))) } ``` -------------------------------- ### Get Current Authenticated Account Source: https://context7.com/heroiclabs/nakama/llms.txt Retrieves the details of the currently authenticated user account. ```APIDOC ## GET /v2/account ### Description Retrieves the details of the currently authenticated user account. ### Method GET ### Endpoint /v2/account ### Response #### Success Response (200) - **user** (object) - User details. - **id** (string) - User ID. - **username** (string) - Username. - **display_name** (string) - Display name. - **avatar_url** (string) - URL of the user's avatar. - **lang_tag** (string) - User's language tag. - **location** (string) - User's location. - **timezone** (string) - User's timezone. - **metadata** (string) - User's metadata (JSON string). - **online** (boolean) - Whether the user is online. - **create_time** (string) - Timestamp of account creation. - **update_time** (string) - Timestamp of last account update. - **wallet** (string) - User's wallet contents (JSON string). - **email** (string) - User's email address. - **devices** (array) - List of devices linked to the account. - **id** (string) - Device ID. - **verify_time** (string) - Timestamp of account verification. ### Request Example ```shell TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." curl -X GET "http://127.0.0.1:7350/v2/account" \ --header "Authorization: Bearer $TOKEN" ``` ``` -------------------------------- ### Build and Test Roaring Bitmaps Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/RoaringBitmap/roaring/README.md Clone the repository, set GO111MODULE, tidy dependencies, and run tests. ```bash $ git clone git@github.com:RoaringBitmap/roaring.git $ export GO111MODULE=on $ go mod tidy $ go test -v ``` -------------------------------- ### Import GopherLua Package Source: https://github.com/heroiclabs/nakama/blob/master/internal/gopher-lua/README.rst Import the GopherLua package into your Go project to start using its functionalities. ```go import ( "github.com/yuin/gopher-lua" ) ``` -------------------------------- ### Check Lua Table Type in Go Source: https://github.com/heroiclabs/nakama/blob/master/internal/gopher-lua/README.rst Shows how to check if a Lua value is a table and get its length. ```go lv := L.Get(-1) // get the value at the top of the stack if tbl, ok := lv.(*lua.LTable); ok { // lv is LTable fmt.Println(L.ObjLen(tbl)) } ``` -------------------------------- ### Create New FST Builder (To Disk) Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/blevesearch/vellum/README.md Initializes a new FST builder that writes data to a file. Keys must be inserted in lexicographical order before closing the builder. ```go f, err := os.Create("/tmp/vellum.fst") if err != nil { log.Fatal(err) } builder, err := vellum.New(f, nil) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Basic Roaring Bitmap Operations (Go) Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/RoaringBitmap/roaring/README.md Demonstrates creating, manipulating, and serializing 32-bit Roaring bitmaps. Includes operations like union, intersection, and iteration. ```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() } ``` -------------------------------- ### Indexing a Document with Bluge Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/blugelabs/bluge/README.md Demonstrates how to configure and open an index writer, create a new document with a text field, and update the index with the document. Ensure to close the writer when done. ```go config := bluge.DefaultConfig(path) writer, err := bluge.OpenWriter(config) if err != nil { log.Fatalf("error opening writer: %v", err) } defer writer.Close() doc := bluge.NewDocument("example"). AddField(bluge.NewTextField("name", "bluge")) err = writer.Update(doc.ID(), doc) if err != nil { log.Fatalf("error updating document: %v", err) } ``` -------------------------------- ### Run Benchmarks with Real Data Source: https://github.com/heroiclabs/nakama/blob/master/vendor/github.com/RoaringBitmap/roaring/README.md Execute benchmarks using real-world datasets. Ensure the real-roaring-datasets package is installed. ```sh go get github.com/RoaringBitmap/real-roaring-datasets BENCH_REAL_DATA=1 go test -bench BenchmarkRealData -run - ```