### Complete Bedrock Proxy Setup Source: https://github.com/minekube/gate/blob/master/_autodocs/bedrock-proxy.md This Go code demonstrates a complete setup for the Gate proxy with Bedrock support enabled. It includes loading configuration, initializing the Gate instance, accessing both Java and Bedrock proxies, subscribing to player login events for both editions, and starting the proxy. Ensure necessary imports are present. ```go package main import ( "context" "log" "go.minekube.com/gate/pkg/gate" "strings" "go.minekube.com/gate/pkg/proxy" ) func main() { // Load configuration with Bedrock enabled cfg, err := gate.LoadConfig(gate.Viper) if err != nil { log.Fatal("Failed to load config:", err) } // Create Gate instance g, err := gate.New(gate.Options{ Config: cfg, }) if err != nil { log.Fatal("Failed to create Gate:", err) } // Access Java and Bedrock proxies javaProxy := g.Java() bedrockProxy := g.Bedrock() if bedrockProxy != nil { log.Println("Bedrock support enabled") } // Subscribe to events for both editions javaProxy.Event().Subscribe(func(e *proxy.PostLoginEvent) { player := e.Player() edition := "Java" if isBedRockPlayer(player) { edition = "Bedrock" } log.Printf("[%s] %s joined", edition, player.Username()) }) // Start proxy (includes Bedrock) if err := g.Start(context.Background()); err != nil { log.Fatal("Proxy error:", err) } } func isBedRockPlayer(player Player) bool { // Bedrock players have dot prefix return strings.HasPrefix(player.Username(), ".") } ``` -------------------------------- ### Bind Address Examples Source: https://github.com/minekube/gate/blob/master/_autodocs/configuration.md Examples demonstrating how to configure the network interface and port for the proxy to listen on. ```yaml bind: "0.0.0.0:25565" # Listen on all interfaces, port 25565 ``` ```yaml bind: "127.0.0.1:25566" # Listen only on localhost, port 25566 ``` ```yaml bind: ":25565" # Equivalent to 0.0.0.0:25565 ``` -------------------------------- ### Start Source: https://github.com/minekube/gate/blob/master/_autodocs/bedrock-proxy.md Starts the Bedrock proxy and initializes Geyser integration. It takes a context for cancellation. ```APIDOC ## Start Proxy ### Description Starts the Bedrock proxy and initializes Geyser integration. It takes a context for cancellation. ### Method `Start` ### Parameters #### Path Parameters - **ctx** (context.Context) - Context for cancellation ### Returns - `error` - error if startup fails ### Request Example ```go err := bedrockProxy.Start(context.Background()) if err != nil { log.Fatal("Failed to start Bedrock proxy:", err) } ``` ``` -------------------------------- ### Example Root Configuration Source: https://github.com/minekube/gate/blob/master/_autodocs/configuration.md A comprehensive example of the Gate configuration file in YAML format, illustrating various settings. ```yaml config: bind: "0.0.0.0:25565" onlineMode: true forwarding: mode: "modern" velocitySecret: "my-secret-key" servers: lobby: "127.0.0.1:25566" survival: "127.0.0.1:25567" try: - lobby - survival status: motd: "§bWelcome to Gate" showMaxPlayers: 1000 bedrock: enabled: false geyser: port: 19132 lite: enabled: false healthService: enabled: false bind: "0.0.0.0:9090" api: enabled: false bind: "0.0.0.0:9091" connect: enabled: false noAutoReload: false ``` -------------------------------- ### Bedrock Proxy Configuration Example Source: https://github.com/minekube/gate/blob/master/_autodocs/bedrock-proxy.md Example YAML configuration for enabling and setting up the Bedrock proxy via Geyser. ```yaml bedrock: enabled: true geyser: port: 19132 bindAddress: "0.0.0.0" # ... more options ``` -------------------------------- ### Floodgate Configuration Example Source: https://github.com/minekube/gate/blob/master/_autodocs/bedrock-proxy.md Example YAML configuration to enable Floodgate for automatic Bedrock player authentication. ```yaml bedrock: enabled: true geyser: floodgate: enabled: true ``` -------------------------------- ### Example: ConnectWithIndication Source: https://github.com/minekube/gate/blob/master/_autodocs/server.md Demonstrates how to use ConnectWithIndication to establish a connection and handle the outcome. ```go server := proxy.Server("survival") req := player.CreateConnectionRequest(server) if req.ConnectWithIndication(context.Background()) { // Connection successful } else { // Proxy has already sent error to player } ``` -------------------------------- ### Start Proxy Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Starts the proxy. This method blocks until the proxy is shut down or an error occurs. It can only be called once. ```go func (p *Proxy) Start(ctx context.Context) error ``` -------------------------------- ### Get Configuration Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Returns a copy of the current proxy configuration settings. ```go func (p *Proxy) Config() config.Config ``` -------------------------------- ### Start Gate Instance Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Starts the Gate proxy and all its underlying processes. This method blocks until the proxy is shut down or an error occurs. ```go ctx := context.Background() if err := g.Start(ctx); err != nil { log.Fatal(err) } ``` -------------------------------- ### Start Bedrock Proxy Source: https://github.com/minekube/gate/blob/master/_autodocs/bedrock-proxy.md Starts the Bedrock proxy service, including Geyser integration. Use a background context for continuous operation. ```Go err := bedrockProxy.Start(context.Background()) if err != nil { log.Fatal("Failed to start Bedrock proxy:", err) } ``` -------------------------------- ### Text Component Configuration Example Source: https://github.com/minekube/gate/blob/master/_autodocs/types.md Demonstrates the configuration format for text components, including color and formatting codes. ```yaml status: motd: "§bWelcome §fto Gate!" ``` -------------------------------- ### Duration Configuration Example Source: https://github.com/minekube/gate/blob/master/_autodocs/types.md Shows how time durations are represented in configuration files, supporting human-readable formats. ```yaml config: connectionTimeout: 5s readTimeout: 30s ``` -------------------------------- ### Handle Proxy Already Run Error Source: https://github.com/minekube/gate/blob/master/_autodocs/errors.md Detect and handle ErrProxyAlreadyRun when attempting to start a Proxy instance that has already been started. ```Go proxy, _ := proxy.New(opts) err1 := proxy.Start(ctx) // First call succeeds err2 := proxy.Start(ctx) // Returns ErrProxyAlreadyRun if errors.Is(err2, proxy.ErrProxyAlreadyRun) { log.Println("Cannot start same proxy twice") } ``` -------------------------------- ### Start Proxy Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Starts the proxy service. This method blocks until the proxy is shut down or an error occurs. It can only be called once. ```APIDOC ## Start Proxy ### Description Starts the proxy and blocks until shutdown or error. A proxy can only be started once. ### Method `Start` ### Parameters None ### Returns - `error` - `ErrProxyAlreadyRun` if called more than once ``` -------------------------------- ### Full Player Connection Flow Example Source: https://github.com/minekube/gate/blob/master/_autodocs/server.md Demonstrates a comprehensive player connection process, including server selection, connection request, and handling various connection statuses and errors. ```go package main import ( "context" "log" "go.minekube.com/gate/pkg/edition/java/proxy" "go.minekube.com/common/minecraft/component" ) func connectPlayerToServer(p proxy.Player, proxyInstance *proxy.Proxy, serverName string) { // Get the target server server := proxyInstance.Server(serverName) if server == nil { p.Disconnect(component.Text{ Content: "Server " + serverName + " not found", }) return } // Create and execute connection request req := p.CreateConnectionRequest(server) result, err := req.Connect(context.Background()) if err != nil { p.Disconnect(component.Text{ Content: "Connection error: " + err.Error(), }) return } // Handle different statuses switch result.Status() { case proxy.SuccessConnectionStatus: log.Printf("%s connected to %s", p.Username(), serverName) case proxy.AlreadyConnectedConnectionStatus: p.SendMessage(component.Text{ Content: "You are already on this server", }) case proxy.ServerDisconnectedConnectionStatus: reason := result.Reason() if reason == nil { reason = component.Text{Content: "Server is unavailable"} } p.Disconnect(reason) default: p.Disconnect(component.Text{ Content: "Failed to connect to server", }) } } ``` -------------------------------- ### Example Usage of UUID String Method Source: https://github.com/minekube/gate/blob/master/_autodocs/types.md Demonstrates how to retrieve and log a player's UUID in its standard string format with dashes. ```go id := player.ID() log.Printf("Player UUID: %s", id.String()) ``` -------------------------------- ### Defining Command Permissions Source: https://github.com/minekube/gate/blob/master/_autodocs/errors.md This example shows how to define permission requirements for a command using `command.Requires`. If the source lacks the specified permission, the command will not be suggested or executable. ```Go // In command definition: cmd := brigodier.Literal("admin"). Requires(command.Requires(func(c *command.RequiresContext) bool { return c.Source.HasPermission("gate.admin") })) // If permission check fails, command won't be suggested or executable ``` -------------------------------- ### Gate.Start Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Starts the Gate instance and all underlying processes. This method blocks until the proxy is shut down or an error occurs. ```APIDOC ## Gate.Start ### Description Starts the Gate instance and all underlying processes (Java proxy, Bedrock proxy, API, etc.). Blocks until the proxy is shutdown or an error occurs. The Proxy is automatically shutdown on method return. ### Method ```go func (g *Gate) Start(ctx context.Context) error ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **ctx** (context.Context) - Context for cancellation and deadline management ### Returns - `error` - Error that occurred during proxy operation ### Request Example ```go ctx := context.Background() if err := g.Start(ctx); err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Common Minecraft Component Examples Source: https://github.com/minekube/gate/blob/master/_autodocs/types.md Illustrates the usage of different types of Minecraft components: Text, Raw JSON, and Translation. ```go // Text component Text{Content: "Hello", Color: color.Green} // JSON component (supports all Minecraft JSON format) &component.Raw{raw} // Translated component &component.Translation{Key: "chat.type.text"} ``` -------------------------------- ### Get Config Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Retrieves a copy of the current proxy configuration. ```APIDOC ## Get Config ### Description Returns a copy of the current proxy configuration. ### Method `Config` ### Parameters None ### Returns - `config.Config` - A copy of the proxy configuration ``` -------------------------------- ### Custom Authentication Server Source: https://github.com/minekube/gate/blob/master/_autodocs/configuration.md Example of setting a custom URL for Mojang's session server. ```yaml auth: sessionServerURL: "https://sessionserver.mojang.com" # Custom auth server ``` -------------------------------- ### Register Plugin Channel Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Example of registering a plugin message channel using the ChannelRegistrar. ```go proxy.ChannelRegistrar().Register( key.New("example:channel"), ) ``` -------------------------------- ### Convenience Function to Start Gate Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md A simplified function to set up and run a Gate instance, automatically handling configuration loading and OS signal management. Supports custom options for configuration and signal handling. ```go ctx := context.Background() err := gate.Start( ctx, gate.WithAutoShutdownOnSignal(true), gate.WithAutoConfigReload("./config.yml"), ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Lite Mode Instance Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Returns the instance for Lite mode functionality. ```go func (p *Proxy) Lite() *lite.Lite ``` -------------------------------- ### Register Server Connection Command Source: https://github.com/minekube/gate/blob/master/_autodocs/commands.md An example of registering a command that allows players to connect to different servers. It uses Brigadier arguments to specify the server name. ```go eventMgr.Subscribe(func(e *proxy.PostLoginEvent) { player := e.Player() cmd := brigodier.Literal("server"). Then(brigodier.Argument("name", brigodier.String()). Executes(command.Command(func(c *command.Context) error { name := c.Argument("name", string.class) server := proxy.Server(name) if server == nil { return c.Source.SendMessage(component.Text{ Content: "Server not found", }) } req := player.CreateConnectionRequest(server) if req.ConnectWithIndication(context.Background()) { return c.Source.SendMessage(component.Text{ Content: "Connected to " + name, }) } return nil }))) proxy.Command().Register(cmd) }) ``` -------------------------------- ### Registering for Events Source: https://github.com/minekube/gate/blob/master/_autodocs/events.md Get the event manager from the proxy instance and subscribe to events using a callback function. ```Go eventMgr := proxy.Event() // Get from proxy instance eventMgr.Subscribe(func(e *ProxyEventType) { // Handle event }) ``` -------------------------------- ### Handle Network Connectivity Errors Source: https://github.com/minekube/gate/blob/master/_autodocs/errors.md This example shows how to handle various network errors that may occur during a connection attempt, such as connection refused or timeouts. ```Go req := player.CreateConnectionRequest(server) result, err := req.Connect(ctx) if err != nil { // Network error occurred player.Disconnect(component.Text{ Content: "Failed to connect to server: " + err.Error(), }) return } ``` -------------------------------- ### Handle KickedFromServerEvent with Fallback Server Source: https://github.com/minekube/gate/blob/master/_autodocs/events.md Implement fallback server logic when a player is kicked from a backend server using KickedFromServerEvent. This example attempts to reconnect the player to a 'fallback' server if they were not already on it. ```go eventMgr.Subscribe(func(e *proxy.KickedFromServerEvent) { if e.Server().Server().ServerInfo().Name() != "fallback" { fallback := proxy.Server("fallback") req := e.Player().CreateConnectionRequest(fallback) req.ConnectWithIndication(context.Background()) } }) ``` -------------------------------- ### Programmatically Validate Configuration Source: https://github.com/minekube/gate/blob/master/_autodocs/configuration.md Example of validating the configuration programmatically using the `Validate` function. This snippet shows how to capture and log validation errors. ```go warns, errs := cfg.Validate() for _, err := range errs { log.Printf("Config error: %v", err) } ``` -------------------------------- ### Subscribe to Bedrock Events Source: https://github.com/minekube/gate/blob/master/_autodocs/bedrock-proxy.md Example of subscribing to a Bedrock-specific event using the proxy's event manager. ```Go bedrockProxy.Event().Subscribe(func(e *bedrock.SomeEvent) { // Handle event }) ``` -------------------------------- ### Get All Registered Servers Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Returns a slice containing all currently registered backend servers. ```go func (p *Proxy) Servers() []RegisteredServer ``` -------------------------------- ### Subscribe to Bedrock Connection Events Source: https://github.com/minekube/gate/blob/master/_autodocs/bedrock-proxy.md Subscribe to proxy events to handle Bedrock player logins. This example shows how to log player names and identify their edition. ```Go eventMgr.Subscribe(func(e *proxy.PostLoginEvent) { player := e.Player() // Works for both Java and Bedrock players log.Printf("%s joined (%s)", player.Username(), getEdition(player)) }) func getEdition(player Player) string { if isBedRockPlayer(player) { return "Bedrock" } return "Java" } ``` -------------------------------- ### Subscribing to Player Disconnect Events Source: https://github.com/minekube/gate/blob/master/_autodocs/errors.md This example demonstrates how to subscribe to player disconnect events and check the `LoginStatus` to determine the reason for disconnection. It logs the player's username and their connection status at the time of disconnect. ```Go eventMgr.Subscribe(func(e *proxy.DisconnectEvent) { player := e.Player() loginStatus := e.LoginStatus() if loginStatus == proxy.LoginStatusConnected { log.Printf("%s disconnected", player.Username()) } else if loginStatus == proxy.LoginStatusWaitingForServer { log.Printf("%s disconnected while connecting to server", player.Username()) } }) ``` -------------------------------- ### Sending Resource Pack with Empty Hash Source: https://github.com/minekube/gate/blob/master/_autodocs/errors.md This example demonstrates sending a resource pack where the hash is invalid (empty). The `SendResourcePack` function expects a 20-byte SHA-1 hash. ```Go pack := ResourcePackInfo{ URL: "https://example.com/pack.zip", Hash: [20]byte{}, // Invalid - empty hash } err := player.SendResourcePack(pack) ``` -------------------------------- ### Get Connection Reason Source: https://github.com/minekube/gate/blob/master/_autodocs/server.md Retrieves the reason for a connection failure, if any. This may return nil. ```go func (cr ConnectionResult) Reason() component.Component ``` -------------------------------- ### Custom Server Selection with PlayerChooseInitialServerEvent Source: https://github.com/minekube/gate/blob/master/_autodocs/events.md Use PlayerChooseInitialServerEvent to customize which server a player connects to upon login. This example redirects VIP players to a specific 'vip-lobby' server. ```go eventMgr.Subscribe(func(e *proxy.PlayerChooseInitialServerEvent) { player := e.Player() if playerIsVIP(player.ID()) { vipServer := proxy.Server("vip-lobby") e.SetInitialServer(vipServer) } }) ``` -------------------------------- ### Adding Plugin to Gate Source: https://github.com/minekube/gate/blob/master/_autodocs/commands.md This Go code snippet demonstrates how to append a custom plugin to the global list of plugins before starting the Minekube Gate proxy. Replace `MyPlugin` with the actual name of your plugin variable. ```go proxy.Plugins = append(proxy.Plugins, MyPlugin) ``` -------------------------------- ### Get Registered Server by Name Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Retrieves a registered backend server by its name. The lookup is case-insensitive. Returns nil if the server is not found. ```go func (p *Proxy) Server(name string) RegisteredServer ``` -------------------------------- ### Register a Literal Command Source: https://github.com/minekube/gate/blob/master/_autodocs/commands.md Registers a simple literal command using Brigadier's builder pattern. This example shows a 'help' command that sends a message to the source. ```go cmd := brigodier.Literal("help"). Executes(command.Command(func(c *command.Context) error { return c.Source.SendMessage(component.Text{ Content: "Help for Gate proxy", }) })) cmdMgr.Register(cmd) ``` -------------------------------- ### gate.Start Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md A convenience function to set up and run a Gate instance with automatic configuration loading and signal handling. ```APIDOC ## gate.Start ### Description A convenience function that sets up and runs a Gate instance with automatic configuration loading and signal handling. ### Method ```go func Start(ctx context.Context, opts ...StartOption) error ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **ctx** (context.Context) - Context for operation - **opts** (...StartOption) - Configuration options ### Start Options: ```go WithConfig(c config.Config) StartOption ``` Provides a pre-loaded Config instead of loading from file. ```go WithAutoShutdownOnSignal(enabled bool) StartOption ``` Enables automatic shutdown on OS signals (enabled by default). ```go WithAutoConfigReload(path string) StartOption ``` Watches a config file for changes and automatically reloads (disabled by default). ### Returns - `error` - Configuration or startup error ### Request Example ```go ctx := context.Background() err := gate.Start( ctx, gate.WithAutoShutdownOnSignal(true), gate.WithAutoConfigReload("./config.yml"), ) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Get Player Client Brand Source: https://github.com/minekube/gate/blob/master/_autodocs/player.md Retrieves the player's client brand, such as 'vanilla', 'fabric', or 'forge'. Returns an empty string if the brand is not specified. ```go func (p Player) ClientBrand() string ``` -------------------------------- ### Create and Initialize Gate Instance Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Instantiates a new Gate instance with provided configuration options. Ensure configuration is loaded and validated before passing it. ```go import ( "context" "go.minekube.com/gate/pkg/gate" "go.minekube.com/gate/pkg/gate/config" ) cfg, err := gate.LoadConfig(gate.Viper) if err != nil { log.Fatal(err) } g, err := gate.New(gate.Options{ Config: cfg, }) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Current Server Connection Source: https://github.com/minekube/gate/blob/master/_autodocs/player.md Returns the current backend server connection, or nil if not connected to any server. Logs the server name if a connection exists. ```go if conn := player.CurrentServer(); conn != nil { serverName := conn.Server().ServerInfo().Name() log.Printf("Player connected to: %s", serverName) } ``` -------------------------------- ### New Source: https://github.com/minekube/gate/blob/master/_autodocs/bedrock-proxy.md Creates a new Bedrock proxy instance. It requires configuration, a Java proxy instance, and optionally accepts an event manager and logger. ```APIDOC ## New Proxy ### Description Creates a new Bedrock proxy instance. It requires configuration, a Java proxy instance, and optionally accepts an event manager and logger. ### Method `New` ### Parameters #### Options Type ```go type Options struct { Config *config.Config JavaProxy *jproxy.Proxy EventMgr event.Manager Logger logr.Logger } ``` #### Parameter Details - **Config** (*config.Config) - Required - Bedrock configuration (must be validated) - **JavaProxy** (*jproxy.Proxy) - Required - Java proxy instance (for integration) - **EventMgr** (event.Manager) - Optional - Event manager for proxy events - **Logger** (logr.Logger) - Optional - Logger instance ### Returns - `*Proxy` - New Bedrock proxy ready to start - `error` - Initialization error ### Request Example ```go import ( "go.minekube.com/gate/pkg/edition/bedrock/proxy" ) bedrockProxy, err := proxy.New(proxy.Options{ Config: bedrockConfig, JavaProxy: javaProxy, }) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Get All Players Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Retrieves a slice containing all currently connected players. ```APIDOC ## Get All Players ### Description Returns a slice of all connected players. ### Method `Players` ### Parameters None ### Returns - `[]Player` - Slice of all connected players ``` -------------------------------- ### Try Server List Source: https://github.com/minekube/gate/blob/master/_autodocs/configuration.md Specify an ordered list of servers to attempt connecting new players to. The first available server in the list will be used. ```yaml try: - lobby - hub - fallback ``` -------------------------------- ### Get Connection Status Source: https://github.com/minekube/gate/blob/master/_autodocs/server.md Retrieves the status code of a connection attempt. ```go func (cr ConnectionResult) Status() ConnectionStatus ``` -------------------------------- ### Switch Player to Another Server Source: https://github.com/minekube/gate/blob/master/_autodocs/README.md This pattern illustrates how to initiate a server switch for a player. It involves creating a connection request and then attempting to connect the player to the target server. ```go req := player.CreateConnectionRequest(server) result, err := req.Connect(ctx) // Check result.Status() ``` -------------------------------- ### Get Player by Name Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Retrieves a player object using their username (case-insensitive). ```APIDOC ## Get Player by Name ### Description Gets a player by username (case-insensitive). ### Method `PlayerByName` ### Parameters #### Path Parameters - **username** (string) - Required - Player username ### Returns - `Player` - The player object, or nil if not connected ``` -------------------------------- ### Loading Configuration Source: https://github.com/minekube/gate/blob/master/_autodocs/errors.md This code loads the application configuration. Ensure the configuration file exists and is readable; otherwise, a file system error will occur. ```Go cfg, err := gate.LoadConfig(gate.Viper) if err != nil { log.Fatalf("Failed to load config: %v", err) } ``` -------------------------------- ### Get All Registered Servers Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Retrieves a slice of all currently registered backend servers. ```APIDOC ## Get All Registered Servers ### Description Returns all registered backend servers. ### Method `Servers` ### Parameters None ### Returns - `[]RegisteredServer` - Slice of RegisteredServer ``` -------------------------------- ### Get Registered Server Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Retrieves a registered backend server by its name (case-insensitive). ```APIDOC ## Get Registered Server ### Description Gets a registered backend server by name (case-insensitive). ### Method `Server` ### Parameters #### Path Parameters - **name** (string) - Required - Server name ### Returns - `RegisteredServer` - The registered server, or nil if not found ``` -------------------------------- ### Import Gate Configuration Package Source: https://github.com/minekube/gate/blob/master/_autodocs/README.md Import the configuration package for Gate. ```go // Configuration import "go.minekube.com/gate/pkg/gate/config" ``` -------------------------------- ### Get Lite Mode Instance Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Retrieves the Lite mode functionality instance. ```APIDOC ## Get Lite Mode Instance ### Description Returns the Lite mode functionality instance. ### Method `Lite` ### Parameters None ### Returns - `*lite.Lite` - The Lite mode instance ``` -------------------------------- ### Import Bedrock Proxy Package Source: https://github.com/minekube/gate/blob/master/_autodocs/README.md Import the package for the Bedrock Edition proxy. ```go // Bedrock proxy import "go.minekube.com/gate/pkg/edition/bedrock/proxy" ``` -------------------------------- ### Get Command Manager Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Retrieves the command manager for registering proxy commands. ```APIDOC ## Get Command Manager ### Description Returns the command manager for registering proxy commands. ### Method `Command` ### Parameters None ### Returns - `*command.Manager` - The command manager instance ``` -------------------------------- ### Accessing Command Context and Source Source: https://github.com/minekube/gate/blob/master/_autodocs/commands.md Demonstrates how to access parsed arguments and the command source within a command handler. The Source interface allows sending messages back to the originator. ```go command.Command(func(c *command.Context) error { // Access parsed arguments playerName := c.Argument("player", string.class) // Access source return c.Source.SendMessage(component.Text{ Content: "You specified: " + playerName, }) }) ``` -------------------------------- ### Get Event Manager Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Retrieves the event manager instance used by the proxy. ```APIDOC ## Get Event Manager ### Description Returns the event manager used by the proxy. ### Method `Event` ### Parameters None ### Returns - `event.Manager` - The event manager instance ``` -------------------------------- ### Create New Java Proxy Instance Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Initializes a new Java edition proxy. Requires a validated configuration and optionally accepts an event manager and a custom authenticator. ```go jproxy, err := proxy.New(proxy.Options{ Config: cfg, }) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Channel Registrar Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Returns the registrar for managing plugin message channels. ```go func (p *Proxy) ChannelRegistrar() *message.ChannelRegistrar ``` -------------------------------- ### Initializing Bedrock Proxy Source: https://github.com/minekube/gate/blob/master/_autodocs/errors.md This code initializes a Bedrock proxy instance. Handle potential errors during initialization, which can occur due to invalid configuration, port conflicts, or network binding issues. ```Go bedrock, err := bproxy.New(bproxy.Options{ Config: bedrockConfig, }) if err != nil { log.Fatalf("Failed to initialize Bedrock proxy: %v", err) } ``` -------------------------------- ### Get All Players Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Returns a slice containing all currently connected player objects. ```go func (p *Proxy) Players() []Player ``` -------------------------------- ### Registering Multiple Commands Source: https://github.com/minekube/gate/blob/master/_autodocs/commands.md Shows how to register various commands, including simple literals, commands with arguments, and commands with permission requirements, using the Brigodier command manager. ```go package main import ( "context" "log" "go.minekube.com/brigodier" "go.minekube.com/common/minecraft/component" "go.minekube.com/gate/pkg/command" "go.minekube.com/gate/pkg/edition/java/proxy" ) func registerCommands(proxy *proxy.Proxy) { cmdMgr := proxy.Command() // Simple command hello := brigodier.Literal("hello"). Executes(command.Command(func(c *command.Context) error { return c.Source.SendMessage(component.Text{ Content: "Hello " + getSourceName(c.Source) + "!", }) })) // Command with arguments msg := brigodier.Literal("msg"). Then(brigodier.Argument("player", brigodier.String()). Then(brigodier.Argument("message", brigodier.GreedyString()). Executes(command.Command(func(c *command.Context) error { playerName := c.Argument("player", string.class) message := c.Argument("message", string.class) target := proxy.PlayerByName(playerName) if target == nil { return c.Source.SendMessage(component.Text{ Content: "Player not found", }) } return target.SendMessage(component.Text{ Content: getSourceName(c.Source) + ": " + message, }) }))). ) // Command with permission requirement admin := brigodier.Literal("admin"). Requires(command.Requires(func(c *command.RequiresContext) bool { return c.Source.HasPermission("gate.admin") })). Then(brigodier.Literal("reload"). Executes(command.Command(func(c *command.Context) error { // Reload logic here return c.Source.SendMessage(component.Text{ Content: "Config reloaded", }) }))) // Register all commands cmdMgr.Register(hello) cmdMgr.Register(msg) cmdMgr.Register(admin) } func getSourceName(src command.Source) string { if player, ok := src.(proxy.Player); ok { return player.Username() } return "Console" } ``` -------------------------------- ### Get Player by UUID Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Retrieves a player object using their unique identifier (UUID). ```APIDOC ## Get Player by UUID ### Description Gets a player by UUID. ### Method `Player` ### Parameters #### Path Parameters - **id** (uuid.UUID) - Required - Player UUID ### Returns - `Player` - The player object, or nil if not connected ``` -------------------------------- ### Get Player Count Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Returns the total number of players currently connected to the proxy. ```APIDOC ## Get Player Count ### Description Returns the number of connected players. ### Method `PlayerCount` ### Parameters None ### Returns - `int` - The number of connected players ``` -------------------------------- ### Create ServerInfo Instance Source: https://github.com/minekube/gate/blob/master/_autodocs/server.md Creates a new ServerInfo instance used to represent basic information about a backend Minecraft server. Requires a name for identification and a net.Addr for the network address. ```go addr, _ := net.ResolveTCPAddr("tcp", "backend.example.com:25565") info := NewServerInfo("lobby", addr) ``` -------------------------------- ### Get Player Count Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Returns the total number of players currently connected to the proxy. ```go func (p *Proxy) PlayerCount() int ``` -------------------------------- ### Handle Missing Configuration Error Source: https://github.com/minekube/gate/blob/master/_autodocs/errors.md Check for ErrMissingConfig when initializing Gate or Proxy if configuration is not provided. ```Go gate, err := gate.New(gate.Options{ Config: nil, // Returns ErrMissingConfig }) if err == errs.ErrMissingConfig { log.Fatal("Config is required") } ``` -------------------------------- ### Get Command Manager Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Retrieves the command manager for registering custom proxy commands. ```go func (p *Proxy) Command() *command.Manager ``` -------------------------------- ### Import Java Proxy Package Source: https://github.com/minekube/gate/blob/master/_autodocs/README.md Import the package for the Java Edition proxy. ```go // Java proxy import "go.minekube.com/gate/pkg/edition/java/proxy" ``` -------------------------------- ### Get Server for Connection Source: https://github.com/minekube/gate/blob/master/_autodocs/server.md Retrieves the registered server associated with an active server connection. ```go func (sc ServerConnection) Server() RegisteredServer ``` -------------------------------- ### Handling Unknown Commands Source: https://github.com/minekube/gate/blob/master/_autodocs/errors.md This snippet demonstrates how to execute a command and check for errors, specifically handling cases where the command is not recognized by the proxy. ```Go results := proxy.Command().Parse(ctx, source, "/invalidcmd") err := proxy.Command().Execute(results) if err != nil { // Handle unknown command } ``` -------------------------------- ### Get Event Manager Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Retrieves the event manager instance used by the proxy to handle events. ```go func (p *Proxy) Event() event.Manager ``` -------------------------------- ### Get Pending Resource Packs Source: https://github.com/minekube/gate/blob/master/_autodocs/player.md Retrieves a slice of all resource packs currently being sent to the player. ```go func (p Player) PendingResourcePacks() []*ResourcePackInfo ``` -------------------------------- ### Get Applied Resource Packs Source: https://github.com/minekube/gate/blob/master/_autodocs/player.md Retrieves a slice of all resource packs that have been applied or accepted by the player. ```go func (p Player) AppliedResourcePacks() []*ResourcePackInfo ``` -------------------------------- ### proxy.New Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Creates a new Java proxy instance with the provided options. ```APIDOC ## proxy.New ### Description Creates a new Java proxy instance. ### Method ```go func New(options Options) (*Proxy, error) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (Options) - Required - Proxy configuration options ### Options Type: ```go type Options struct { Config *config.Config EventMgr event.Manager Authenticator auth.Authenticator } ``` ### Returns: - `*Proxy` - New proxy ready to start - `error` - Initialization error ### Example: ```go jproxy, err := proxy.New(proxy.Options{ Config: cfg, }) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Import Command System Package Source: https://github.com/minekube/gate/blob/master/_autodocs/README.md Import the package for the command system. ```go // Command system import "go.minekube.com/gate/pkg/command" ``` -------------------------------- ### Create New Bedrock Proxy Source: https://github.com/minekube/gate/blob/master/_autodocs/bedrock-proxy.md Instantiates a new Bedrock proxy. Ensure the provided config is validated and the Java proxy is properly initialized. ```Go import ( "go.minekube.com/gate/pkg/edition/bedrock/proxy" ) bedrockProxy, err := proxy.New(proxy.Options{ Config: bedrockConfig, JavaProxy: javaProxy, }) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Channel Registrar Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Returns the registrar for plugin message channels, allowing registration of new channels. ```APIDOC ## Get Channel Registrar ### Description Returns the registrar for plugin message channels. ### Example ```go proxy.ChannelRegistrar().Register( key.New("example:channel"), ) ``` ### Method `ChannelRegistrar` ### Parameters None ### Returns - `*message.ChannelRegistrar` - The channel registrar instance ``` -------------------------------- ### Import Permission Utility Package Source: https://github.com/minekube/gate/blob/master/_autodocs/README.md Import the utility package for permission management. ```go import "go.minekube.com/gate/pkg/util/permission" ``` -------------------------------- ### Import Java Edition Configuration Package Source: https://github.com/minekube/gate/blob/master/_autodocs/README.md Import the configuration package specific to the Java Edition. ```go import "go.minekube.com/gate/pkg/edition/java/config" ``` -------------------------------- ### Import Main Gate Package Source: https://github.com/minekube/gate/blob/master/_autodocs/README.md Import the main Gate package for core functionality. ```go // Main Gate package import "go.minekube.com/gate/pkg/gate" ``` -------------------------------- ### Get Player by Username Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Retrieves a player object by their username. The lookup is case-insensitive. Returns nil if the player is not connected. ```go func (p *Proxy) PlayerByName(username string) Player ``` -------------------------------- ### Get Player by UUID Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Retrieves a player object using their unique UUID. Returns nil if the player is not connected. ```go func (p *Proxy) Player(id uuid.UUID) Player ``` -------------------------------- ### Connect Player with Indication Source: https://github.com/minekube/gate/blob/master/_autodocs/server.md Connects a player to a server using the proxy's built-in error handling for automatic player feedback. Returns true on success. ```go func (cr ConnectionRequest) ConnectWithIndication(ctx context.Context) bool ``` -------------------------------- ### Import Color Package Source: https://github.com/minekube/gate/blob/master/_autodocs/README.md Import the package for handling Minecraft colors in components. ```go import "go.mine.kube.com/common/minecraft/color" ``` -------------------------------- ### Players Interface Source: https://github.com/minekube/gate/blob/master/_autodocs/server.md A thread-safe collection for managing players, offering methods to get the player count and iterate through connected players. ```APIDOC ## Players Interface Thread-safe collection of players. ### Methods #### Len ```go func (p Players) Len() int ``` Returns the number of players in the collection. **Returns:** Player count #### Range ```go func (p Players) Range(fn func(p Player) bool) ``` Iterates through all players. The iteration stops if the callback returns false. **Parameters:** | Parameter | Type | Description | |-----------|------|-------------| | fn | func(p Player) bool | Callback function (return false to stop iteration) | **Example:** ```go server.Players().Range(func(p Player) bool { log.Printf("Player: %s", p.Username()) return true // continue iteration }) ``` ``` -------------------------------- ### Event Registration Source: https://github.com/minekube/gate/blob/master/_autodocs/events.md Demonstrates how to obtain the event manager instance and subscribe to events. ```APIDOC ## Event Registration Obtain the event manager from the proxy instance and subscribe to events. ### Method Signature ```go eventMgr := proxy.Event() ``` ### Subscription Example ```go eventMgr.Subscribe(func(e *ProxyEventType) { // Handle event }) ``` ``` -------------------------------- ### Get Deprecated Applied Resource Pack Source: https://github.com/minekube/gate/blob/master/_autodocs/player.md Deprecated: Returns the single resource pack that was applied. Use AppliedResourcePacks() for multiple packs. ```go func (p Player) AppliedResourcePack() *ResourcePackInfo ``` -------------------------------- ### Registering Commands in a Plugin Source: https://github.com/minekube/gate/blob/master/_autodocs/commands.md This Go code snippet shows how to define a plugin and register custom commands during its initialization phase. Ensure the `registerCommands` function is implemented to handle command registration. ```go var Plugin = proxy.Plugin{ Name: "custom-commands", Init: func(ctx context.Context, p *proxy.Proxy) error { registerCommands(p) return nil }, } ``` -------------------------------- ### Override Configuration with Environment Variables Source: https://github.com/minekube/gate/blob/master/_autodocs/configuration.md Example of setting an environment variable to override a configuration value. The `VELOCITY_SECRET` variable is used here to set `forwarding.velocitySecret`. ```bash export VELOCITY_SECRET="my-secret-key" gate # Uses env var instead of config file value ``` -------------------------------- ### Get Deprecated Pending Resource Pack Source: https://github.com/minekube/gate/blob/master/_autodocs/player.md Deprecated: Returns the single resource pack currently being sent. Use PendingResourcePacks() for multiple packs. ```go func (p Player) PendingResourcePack() *ResourcePackInfo ``` -------------------------------- ### Validate Configuration and Handle Errors Source: https://github.com/minekube/gate/blob/master/_autodocs/errors.md Use this snippet to validate configuration settings and log any validation errors that occur. ```Go warns, errs := config.Validate() if len(errs) > 0 { for _, err := range errs { log.Printf("Validation error: %v", err) } return fmt.Errorf("configuration has %d errors", len(errs)) } ``` -------------------------------- ### Subscribe to PostLoginEvent Source: https://github.com/minekube/gate/blob/master/_autodocs/events.md Subscribe to the PostLoginEvent to execute logic after a player has successfully logged in and is ready to connect to a server. This snippet shows how to send a welcome message to the player. ```go eventMgr.Subscribe(func(e *proxy.PostLoginEvent) { player := e.Player() player.SendMessage(component.Text{ Content: "Welcome " + player.Username() + "!", }) }) ``` -------------------------------- ### Register New Server Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Registers a new backend server with the proxy. Requires server information including name and address. Returns an error if the server already exists or the address is invalid. ```go func (p *Proxy) Register(info ServerInfo) (RegisteredServer, error) ``` -------------------------------- ### Filter Server Connections with ServerPreConnectEvent Source: https://github.com/minekube/gate/blob/master/_autodocs/events.md Intercept connections before they are established using ServerPreConnectEvent. This example redirects players to a 'lobby' server if the target server is in maintenance mode. ```go eventMgr.Subscribe(func(e *proxy.ServerPreConnectEvent) { player := e.Player() server := e.Server() if isMaintenanceMode(server) { e.SetServer(proxy.Server("lobby")) } }) ``` -------------------------------- ### Import UUID Utility Package Source: https://github.com/minekube/gate/blob/master/_autodocs/README.md Import the utility package for handling UUIDs. ```go // Utilities import "go.minekube.com/gate/pkg/util/uuid" ``` -------------------------------- ### Connect Player to a Server Source: https://github.com/minekube/gate/blob/master/_autodocs/server.md Initiates a connection for a player to a target server. This method blocks until the player logs on or an error occurs. Handles connection success and failure, disconnecting the player if the connection is unsuccessful. ```go server := proxy.Server("lobby") req := player.CreateConnectionRequest(server) result, err := req.Connect(context.Background()) if err != nil { player.Disconnect(component.Text{Content: "Network error: " + err.Error()}) return } if !result.Status().Successful() { reason := result.Reason() if reason == nil { reason = component.Text{Content: "Server rejected connection"} } player.Disconnect(reason) return } // Connection successful ``` -------------------------------- ### Get Player Context Source: https://github.com/minekube/gate/blob/master/_autodocs/player.md Retrieves the player's context which is canceled when the connection closes. Useful for managing background operations tied to the player's session. ```go go func(ctx context.Context) { select { case <-ctx.Done(): log.Println("Player disconnected") case <-time.After(30 * time.Second): log.Println("30 seconds passed") } }(player.Context()) ``` -------------------------------- ### Attaching Source to Context Source: https://github.com/minekube/gate/blob/master/_autodocs/commands.md Offers a utility function to create a new context that includes a specific command Source. This is useful for passing source information down through nested function calls. ```go func ContextWithSource(ctx context.Context, src Source) context.Context ``` -------------------------------- ### Denying Pre-Login with Reason Source: https://github.com/minekube/gate/blob/master/_autodocs/events.md Use PreLoginEvent to perform checks before a player logs in. Deny access with a specific reason if checks fail. ```Go eventMgr.Subscribe(func(e *proxy.PreLoginEvent) { username := e.Username() // Whitelist check if !isWhitelisted(username) { e.Deny(component.Text{Content: "You are not whitelisted"}) } }) ``` -------------------------------- ### Gate Core API Source: https://github.com/minekube/gate/blob/master/_autodocs/README.md Documentation for the main Gate instance and Java proxy API, including server and player management, configuration loading, and convenience functions. ```APIDOC ## Gate Core API ### Description Provides access to the root proxy instance and the Java Edition proxy. Allows for managing servers, players, and loading configurations. ### Methods - `New()`: Constructor for the Gate proxy. - `Start()`: Starts the proxy server. - `Shutdown()`: Gracefully shuts down the proxy server. - `Server()`: Retrieves information about a specific server. - `Servers()`: Retrieves a list of all registered servers. - `Player()`: Retrieves information about a specific player. - `Players()`: Retrieves a list of all connected players. - `Register()`: Registers a new server. - `Unregister()`: Unregisters a server. ### Key Types - `Gate`: The root proxy holder. - `Proxy`: Represents the Java Edition proxy with full player and server management capabilities. - `Options`: Configuration options for both Gate and Proxy. ``` -------------------------------- ### Subscribe to PostLoginEvent Source: https://github.com/minekube/gate/blob/master/_autodocs/events.md Subscribe to the PostLoginEvent to perform actions when a player successfully logs in. Access player information via the event. ```go eventMgr.Subscribe(func(e *proxy.PostLoginEvent) { player := e.Player() // Handle event }) ``` -------------------------------- ### Handle Server Registration Error for Existing Server Source: https://github.com/minekube/gate/blob/master/_autodocs/errors.md Attempt to register servers and handle the error returned when trying to register a server with a name that already exists. ```Go info1 := NewServerInfo("lobby", addr1) _, err1 := proxy.Register(info1) // Succeeds info2 := NewServerInfo("lobby", addr2) // Same name _, err2 := proxy.Register(info2) // Returns error ``` -------------------------------- ### Enable Lite Mode Proxy Source: https://github.com/minekube/gate/blob/master/_autodocs/configuration.md Configure the lightweight proxy mode for simple port forwarding. This snippet shows how to enable lite mode and initialize the routes. ```yaml lite: enabled: false routes: [] ``` -------------------------------- ### gate.New Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Creates and returns a new Gate instance with the provided options. This is the primary constructor for the Gate type. ```APIDOC ## gate.New ### Description Creates and returns a new Gate instance with the provided options. ### Method ```go func New(options Options) (*Gate, error) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (Options) - Required - Gate configuration options ### Options Type ```go type Options struct { Config *config.Config EventMgr event.Manager } ``` ### Returns - `*Gate` - A new Gate instance ready to start - `error` - Configuration validation or initialization error ### Throws - `errs.ErrMissingConfig` - When Config is nil - Validation errors from config.Validate() ### Request Example ```go import ( "context" "go.minekube.com/gate/pkg/gate" "go.minekube.com/gate/pkg/gate/config" ) cfg, err := gate.LoadConfig(gate.Viper) if err != nil { log.Fatal(err) } g, err := gate.New(gate.Options{ Config: cfg, }) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### ConnectionRequest.ConnectWithIndication Source: https://github.com/minekube/gate/blob/master/_autodocs/server.md Initiates a connection to a server using the proxy's built-in error handling. Errors are automatically provided to the player if the connection fails. ```APIDOC ## ConnectWithIndication ### Description Initiates a connection to a server using the proxy's built-in error handling. Errors are automatically provided to the player if the connection fails. Returns true if the connection was successful. ### Method `ConnectWithIndication` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go server := proxy.Server("survival") req := player.CreateConnectionRequest(server) if req.ConnectWithIndication(context.Background()) { // Connection successful } else { // Proxy has already sent error to player } ``` ### Response #### Success Response `bool`: true if successfully connected, false otherwise. #### Response Example `true` or `false` ``` -------------------------------- ### Register a Command Source: https://github.com/minekube/gate/blob/master/_autodocs/README.md This snippet demonstrates how to register a new command using the Brigadier framework. The command is defined with a literal name and an execution function. ```go cmd := brigodier.Literal("name"). Executes(command.Command(func(c *command.Context) error { // Execute command })) proxy.Command().Register(cmd) ``` -------------------------------- ### Register Admin Command with Permission Source: https://github.com/minekube/gate/blob/master/_autodocs/commands.md Registers an 'admin' command that requires the 'gate.admin' permission. Only sources with this permission can execute the command. ```go cmd := brigodier.Literal("admin"). Requires(command.Requires(func(c *command.RequiresContext) bool { return c.Source.HasPermission("gate.admin") })). Executes(command.Command(func(c *command.Context) error { return c.Source.SendMessage(component.Text{ Content: "Admin command executed", }) })) proxy.Command().Register(cmd) ``` -------------------------------- ### Define Authentication Configuration Source: https://github.com/minekube/gate/blob/master/_autodocs/types.md Defines the authentication settings, including a custom Mojang session server URL. ```go type Auth struct { SessionServerURL *configutil.URL } ``` -------------------------------- ### Specify Configuration File Path Source: https://github.com/minekube/gate/blob/master/_autodocs/configuration.md Command-line argument to specify a custom path for the configuration file. This allows loading configuration from a location other than the default. ```bash gate --config /path/to/config.yml ``` -------------------------------- ### Register Server Source: https://github.com/minekube/gate/blob/master/_autodocs/gate-proxy.md Registers a new backend server with the proxy. ```APIDOC ## Register Server ### Description Registers a new backend server. ### Method `Register` ### Parameters #### Path Parameters - **info** (ServerInfo) - Required - Server information (name and address) ### Returns - `RegisteredServer` - The registered server - `error` - Error if server already exists or invalid address ```