### Install Kite Framework using Go Source: https://github.com/koding/kite/blob/master/README.md Installs the Kite micro-service framework package using the Go get command. This is the initial step to start using Kite in your Go projects. ```bash go get github.com/koding/kite ``` -------------------------------- ### Kontrol Server Setup and Configuration in Go Source: https://context7.com/koding/kite/llms.txt Provides a basic setup for the Kontrol server, which acts as a central registry for Koding kites. It demonstrates initializing Kontrol with configuration, setting up storage, and optionally customizing machine authentication and key selection logic. ```go package main import ( "github.com/koding/kite" "github.com/koding/kite/kontrol" ) func main() { // Create Kontrol instance k := kontrol.New(&kontrol.Config{ Username: "kontrol", KiteKey: "kontrol-kite-key", PublicKey: "-----BEGIN PUBLIC KEY-----\n...", PrivateKey: "-----BEGIN RSA PRIVATE KEY-----\n...", Port: 6000, }, "1.0.0") // Configure storage backend (etcd, postgres, etc.) k.SetStorage(yourStorageImplementation) // Optional: Custom machine authentication k.MachineAuthenticate = func(authType string, r *kite.Request) error { // Implement custom authentication logic return nil } // Optional: Custom key picker for multiple key pairs k.MachineKeyPicker = func(r *kite.Request) (*kontrol.KeyPair, error) { // Return appropriate key pair based on request return &kontrol.KeyPair{ ID: "key-id", Public: "public-key-pem", Private: "private-key-pem", }, nil } // Start Kontrol server k.Kite.Run() } ``` -------------------------------- ### Install Kontrol Service Registry using Go Source: https://github.com/koding/kite/blob/master/README.md Installs the Kontrol service, which acts as a service registry and authentication service for Kites. It is installed using the Go get command. ```bash go get github.com/koding/kite/kontrol/kontrol ``` -------------------------------- ### Create and Run a Go Kite Server Source: https://context7.com/koding/kite/llms.txt This Go code snippet demonstrates how to create a new Kite micro-service, register a method handler ('square'), configure the server port, and start the Kite server. It requires the 'github.com/koding/kite' package. ```go package main import "github.com/koding/kite" func main() { // Create a new kite with name and semantic version k := kite.New("math", "1.0.0") // Register a method handler k.HandleFunc("square", func(r *kite.Request) (interface{}, error) { // Extract argument a := r.Args.One().MustFloat64() result := a * a return result, nil }).DisableAuthentication() // Configure server port k.Config.Port = 3636 // Start the server (blocking call) k.Run() } ``` -------------------------------- ### Custom HTTP Handlers and Routes in Go Source: https://context7.com/koding/kite/llms.txt Demonstrates how to register custom kite methods, add HTTP endpoints for health checks and REST APIs, and serve static files using the kite.go library. It covers defining handlers for GET and POST requests and serving files from a 'public' directory. ```go package main import ( "encoding/json" "fmt" "net/http" "github.com/koding/kite" ) func main() { k := kite.New("webservice", "1.0.0") // Register kite methods k.HandleFunc("kiteMethod", func(r *kite.Request) (interface{}, error) { return "kite response", nil }) // Add custom HTTP endpoint k.HandleHTTPFunc("/health", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{ "status": "healthy", "service": "webservice", }) }) // Add REST API endpoint k.HandleHTTPFunc("/api/users", func(w http.ResponseWriter, r *http.Request) { switch r.Method { case "GET": users := []map[string]string{ {"id": "1", "name": "Alice"}, {"id": "2", "name": "Bob"}, } json.NewEncoder(w).Encode(users) case "POST": w.WriteHeader(http.StatusCreated) fmt.Fprintf(w, "User created") default: http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } }) // Serve static files k.HandleHTTP("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./public")))) k.Config.Port = 8080 k.Run() } ``` -------------------------------- ### Method Throttling and Rate Limiting in Go Source: https://context7.com/koding/kite/llms.txt This Go code illustrates how to implement method throttling and rate limiting in Koding Kite. It shows how to configure limits on specific methods to control the request rate and manage burst capacity, preventing overload and ensuring fair usage. The example includes testing the throttling mechanism by making rapid client requests. ```go package main import ( "fmt" "time" "github.com/koding/kite" ) func main() { k := kite.New("api", "1.0.0") // Throttle method to 10 requests per second // fillInterval: 100ms (1000ms / 10 = 100ms per token) // capacity: 10 (max burst of 10 requests) k.HandleFunc("limited", func(r *kite.Request) (interface{}, error) { return "success", nil }).Throttle(100*time.Millisecond, 10) // Throttle to 30 requests per second with burst capacity // fillInterval: 33.33ms (1000ms / 30 ≈ 33ms) // capacity: 50 (allows burst of 50 requests) k.HandleFunc("burst", func(r *kite.Request) (interface{}, error) { return "processed", nil }).Throttle(33*time.Millisecond, 50) k.Config.Port = 5001 go k.Run() <-k.ServerReadyNotify() // Test throttling client := k.NewClient(fmt.Sprintf("http://localhost:%d/kite", k.Port())) client.Dial() // Make multiple rapid requests for i := 0; i < 15; i++ { resp, err := client.Tell("limited") if err != nil { // After 10 requests, will receive rate limit error fmt.Printf("Request %d: %s\n", i+1, err.Error()) } else { fmt.Printf("Request %d: %s\n", i+1, resp.MustString()) } } } ``` -------------------------------- ### Import Kite Package in Go Source: https://github.com/koding/kite/blob/master/README.md Demonstrates how to import the Kite package into your Go source files. This allows you to use Kite's functionalities by referring to it with the alias 'kite'. ```go import "github.com/koding/kite" // Use 'kite' as the package name for Kite functionalities. ``` -------------------------------- ### Register Go Kite with Kontrol Service Discovery Source: https://context7.com/koding/kite/llms.txt This Go code snippet illustrates how to configure a Kite micro-service to register with the Kontrol service discovery system. It includes setting up Kite with Kontrol URL and authentication, defining Kite properties, registering a method, and initiating the registration process when the server is ready. It requires 'github.com/koding/kite' and 'github.com/koding/kite/config'. ```go package main import ( "github.com/koding/kite" "github.com/koding/kite/config" ) func main() { // Create configuration with Kontrol URL and credentials cfg := config.New() cfg.KontrolURL = "http://kontrol.example.com:6000/kite" cfg.KiteKey = "your-kite-key-jwt-token" // Create kite with configuration k := kite.NewWithConfig("worker", "1.0.0", cfg) // Set up kite properties k.Config.IP = "0.0.0.0" k.Config.Port = 4000 k.Config.Environment = "production" k.Config.Region = "us-west" // Register a method k.HandleFunc("process", func(r *kite.Request) (interface{}, error) { return "processed", nil }) // Register with Kontrol when kite starts go func() { <-k.ServerReadyNotify() err := k.RegisterHTTPForever(&k.Config.KontrolURL) if err != nil { k.Log.Error("Registration failed: %s", err) } }() // Start the server k.Run() } ``` -------------------------------- ### Authentication and Authorization in Go Source: https://context7.com/koding/kite/llms.txt Illustrates how to implement custom authentication mechanisms and control access to kite methods. It shows how to define a custom authenticator, protect methods by default, disable authentication for specific methods, and configure client-side authentication. ```go package main import ( "fmt" "github.com/koding/kite" ) func main() { k := kite.New("authservice", "1.0.0") // Custom authenticator k.Authenticators["customToken"] = func(r *kite.Request) error { token := r.Auth.Key // Validate custom token if token != "valid-token-123" { return fmt.Errorf("invalid token") } // Set authenticated username r.Username = "authenticated-user" return nil } // Method with authentication required (default) k.HandleFunc("protected", func(r *kite.Request) (interface{}, error) { return fmt.Sprintf("Hello %s", r.Username), nil }) // Method without authentication k.HandleFunc("public", func(r *kite.Request) (interface{}, error) { return "public data", nil }).DisableAuthentication() // Global authentication disable (not recommended for production) k.Config.DisableAuthentication = true k.Config.Port = 7000 go k.Run() <-k.ServerReadyNotify() // Client with authentication client := k.NewClient("http://localhost:7000/kite") client.Auth = &kite.Auth{ Type: "customToken", Key: "valid-token-123", } client.Dial() resp, err := client.Tell("protected") if err != nil { fmt.Printf("Error: %s\n", err) } else { fmt.Printf("Response: %s\n", resp.MustString()) } } ``` -------------------------------- ### Koding Kite TLS/HTTPS Configuration (Go) Source: https://context7.com/koding/kite/llms.txt Demonstrates various methods for configuring TLS/HTTPS in Koding Kite. It covers loading certificates from files, using certificate strings directly, and advanced configuration using `tls.Config` for minimum TLS version and cipher suites. ```go package main import ( "crypto/tls" "github.com/koding/kite" ) func main() { k := kite.New("secure", "1.0.0") k.HandleFunc("secureMethod", func(r *kite.Request) (interface{}, error) { return "secure response", nil }) // Option 1: Load TLS certificates from files k.UseTLSFile("/path/to/cert.pem", "/path/to/key.pem") // Option 2: Use certificate strings certPEM := `-----BEGIN CERTIFICATE----- MIIDXTCCAkWgAwIBAgIJAK... -----END CERTIFICATE-----` keyPEM := `-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEA0... -----END RSA PRIVATE KEY-----` k.UseTLS(certPEM, keyPEM) // Option 3: Advanced TLS configuration k.TLSConfig = &tls.Config{ MinVersion: tls.VersionTLS12, CipherSuites: []uint16{ tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, }, PreferServerCipherSuites: true, } k.Config.Port = 8443 k.Run() } ``` -------------------------------- ### Query Kites from Kontrol with Go Source: https://context7.com/koding/kite/llms.txt This Go code snippet demonstrates how to use the Koding Kite library to connect to Kontrol, query for specific kites based on criteria, and then make RPC calls to the discovered kites. It includes error handling and connection management for both Kontrol and individual kites. ```go package main import ( "fmt" "github.com/koding/kite" "github.com/koding/kite/protocol" ) func main() { k := kite.New("client", "1.0.0") k.Config.KontrolURL = "http://kontrol.example.com:6000/kite" k.Config.KiteKey = "your-kite-key-jwt-token" // Connect to Kontrol err := k.SetupKontrolClient() if err != nil { panic(err) } // Query for kites by name query := &protocol.KontrolQuery{ Username: "user1", Environment: "production", Name: "worker", } kites, err := k.GetKites(query) if err != nil { panic(err) } fmt.Printf("Found %d kites\n", len(kites)) for _, kiteInfo := range kites { fmt.Printf("Kite: %s at %s\n", kiteInfo.Kite.Name, kiteInfo.URL) // Connect to discovered kite client := k.NewClient(kiteInfo.URL) client.Auth = &kite.Auth{ Type: "token", Key: kiteInfo.Token, } err := client.Dial() if err != nil { fmt.Printf("Connection error: %s\n", err) continue } // Make RPC call response, _ := client.Tell("process") fmt.Printf("Response: %s\n", response.MustString()) client.Close() } } ``` -------------------------------- ### Method Handlers with Pre and Post Middleware in Go Source: https://context7.com/koding/kite/llms.txt This Go code demonstrates how to define method handlers in Koding Kite and augment them with pre and post middleware functions. It shows global middleware applicable to all methods, as well as method-specific middleware for fine-grained control over request processing and response formatting. ```go package main import ( "context" "fmt" "github.com/koding/kite" ) func main() { k := kite.New("api", "1.0.0") // Global pre-handler executed before all methods k.PreHandleFunc(func(r *kite.Request) (interface{}, error) { fmt.Println("Global pre-handler: authenticating request") r.Context = context.WithValue(r.Context, "timestamp", "2024-01-01") return nil, nil }) // Global post-handler executed after all methods k.PostHandleFunc(func(r *kite.Request) (interface{}, error) { fmt.Println("Global post-handler: logging request") return nil, nil }) // Method-specific handlers k.HandleFunc("calculate", func(r *kite.Request) (interface{}, error) { num := r.Args.One().MustFloat64() result := num * 2 r.Context = context.WithValue(r.Context, "result", result) return result, nil }).PreHandleFunc(func(r *kite.Request) (interface{}, error) { // Validate input before calculation fmt.Println("Method pre-handler: validating input") return nil, nil }).PostHandleFunc(func(r *kite.Request) (interface{}, error) { // Format output after calculation fmt.Println("Method post-handler: formatting output") result := r.Context.Value("result").(float64) return result, nil }) k.Config.Port = 5000 k.Run() } ``` -------------------------------- ### Koding Kite Handling Complex Request Arguments (Go) Source: https://context7.com/koding/kite/llms.txt Illustrates how to handle complex and multiple arguments in Koding Kite requests. It shows defining request and response structs, unmarshalling arguments into structs, validating input, and making calls with structured and multiple arguments from a client. ```go package main import ( "fmt" "github.com/koding/kite" ) type UserRequest struct { Name string `json:"name"` Email string `json:"email"` Age int `json:"age"` } type UserResponse struct { ID string `json:"id"` Message string `json:"message"` } func main() { k := kite.New("userservice", "1.0.0") // Handler with structured arguments k.HandleFunc("createUser", func(r *kite.Request) (interface{}, error) { var req UserRequest if err := r.Args.One().Unmarshal(&req); err != nil { return nil, fmt.Errorf("invalid arguments: %s", err) } // Validate input if req.Name == "" { return nil, fmt.Errorf("name is required") } // Process request response := UserResponse{ ID: "user-123", Message: fmt.Sprintf("User %s created", req.Name), } return response, nil }) // Handler with multiple arguments k.HandleFunc("sendMessage", func(r *kite.Request) (interface{}, error) { args := r.Args.MustSliceOfLength(3) recipient := args[0].MustString() subject := args[1].MustString() body := args[2].MustString() fmt.Printf("Sending to %s: %s\n", recipient, subject) return map[string]string{ "status": "sent", "to": recipient, }, nil }) k.Config.Port = 6000 go k.Run() <-k.ServerReadyNotify() // Client making calls client := k.NewClient("http://localhost:6000/kite") client.Dial() // Call with structured argument resp1, err := client.Tell("createUser", UserRequest{ Name: "John Doe", Email: "john@example.com", Age: 30, }) if err != nil { panic(err) } var userResp UserResponse resp1.Unmarshal(&userResp) fmt.Printf("Created: %s\n", userResp.Message) // Call with multiple arguments resp2, _ := client.Tell("sendMessage", "alice@example.com", "Hello", "Message body") fmt.Printf("Status: %v\n", resp2) } ``` -------------------------------- ### Koding Kite Connection Lifecycle Handlers (Go) Source: https://context7.com/koding/kite/llms.txt Demonstrates how to define and use connection lifecycle handlers in Koding Kite. This includes functions for client connections, first requests, disconnections, and successful registration. It also shows client-side handlers for connection events and token expiration. ```go package main import ( "fmt" "github.com/koding/kite" ) func main() { k := kite.New("server", "1.0.0") // Called when a client connects k.OnConnect(func(client *kite.Client) { fmt.Printf("Client connected: %s\n", client.Kite.Name) }) // Called on first request from client k.OnFirstRequest(func(client *kite.Client) { fmt.Printf("First request from: %s\n", client.Kite.Username) }) // Called when client disconnects k.OnDisconnect(func(client *kite.Client) { fmt.Printf("Client disconnected: %s\n", client.Kite.Name) }) // Called when kite successfully registers with Kontrol k.OnRegister(func(result *protocol.RegisterResult) { fmt.Printf("Registered at URL: %s\n", result.URL) }) // Client-side connection handlers client := k.NewClient("http://localhost:4000/kite") client.OnConnect(func() { fmt.Println("Connected to remote kite") }) client.OnDisconnect(func() { fmt.Println("Disconnected from remote kite") }) client.OnTokenExpire(func() { fmt.Println("Token expired, need to refresh") }) client.OnTokenRenew(func(token string) { fmt.Printf("Token renewed: %s\n", token) }) k.Config.Port = 4000 k.Run() } ``` -------------------------------- ### Connect to a Kite and Make RPC Calls in Go Source: https://context7.com/koding/kite/llms.txt This Go code snippet shows how to create a Kite client, connect to a remote Kite server, and make both synchronous ('Tell') and asynchronous ('Go') RPC calls. It handles connection errors and response processing, requiring 'github.com/koding/kite'. ```go package main import ( "fmt" "github.com/koding/kite" ) func main() { k := kite.New("client", "1.0.0") // Create a client to connect to remote kite client := k.NewClient("http://localhost:3636/kite") // Connect to the remote kite err := client.Dial() if err != nil { panic(err) } defer client.Close() // Make synchronous RPC call response, err := client.Tell("square", 4) if err != nil { panic(err) } result := response.MustFloat64() fmt.Printf("Result: %.0f\n", result) // Output: Result: 16 // Make asynchronous RPC call responseChan := client.Go("square", 5) resp := <-responseChan if resp.Err != nil { panic(resp.Err) } fmt.Printf("Result: %.0f\n", resp.Result.MustFloat64()) // Output: Result: 25 } ``` -------------------------------- ### Connect to and Call a Remote Kite Method in Go Source: https://github.com/koding/kite/blob/master/README.md This Go code demonstrates how to create a client kite, connect to a remote math kite service running on localhost:3636, and invoke its 'square' method with the argument 4. It then prints the result received from the math kite. ```go package main import ( "fmt" "github.com/koding/kite" ) func main() { k := kite.New("exp2", "1.0.0") // Connect to our math kite mathWorker := k.NewClient("http://localhost:3636/kite") mathWorker.Dial() response, _ := mathWorker.Tell("square", 4) // call "square" method with argument 4 fmt.Println("result:", response.MustFloat64()) } ``` -------------------------------- ### Create and Run a Math Kite Service in Go Source: https://github.com/koding/kite/blob/master/README.md This Go code defines a simple math kite service that can calculate the square of a number. It initializes a new kite, registers a 'square' method handler that accepts a float64, disables authentication for this method, sets the port to 3636, and runs the kite service. ```go package main import "github.com/koding/kite" func main() { // Create a kite k := kite.New("math", "1.0.0") // Add our handler method with the name "square" k.HandleFunc("square", func(r *kite.Request) (interface{}, error) { a := r.Args.One().MustFloat64() result := a * a // calculate the square return result, nil // send back the result }).DisableAuthentication() // Attach to a server with port 3636 and run it k.Config.Port = 3636 k.Run() } ``` -------------------------------- ### Go Kite Client with Timeout and Auto-Reconnection Source: https://context7.com/koding/kite/llms.txt This Go snippet demonstrates advanced client connection strategies for Kite micro-services, including establishing connections with a timeout ('DialTimeout') and enabling automatic reconnection ('DialForever'). It also shows making RPC calls with specific timeouts ('TellWithTimeout'). Dependencies include 'github.com/koding/kite' and 'time'. ```go package main import ( "fmt" "time" "github.com/koding/kite" ) func main() { k := kite.New("client", "1.0.0") client := k.NewClient("http://localhost:3636/kite") // Connect with 10-second timeout err := client.DialTimeout(10 * time.Second) if err != nil { panic(err) } // Make RPC call with timeout response, err := client.TellWithTimeout("square", 5*time.Second, 4) if err != nil { panic(err) } fmt.Printf("Result: %.0f\n", response.MustFloat64()) // Enable automatic reconnection client2 := k.NewClient("http://localhost:3636/kite") connected, err := client2.DialForever() if err != nil { panic(err) } // Wait for first successful connection <-connected fmt.Println("Connected successfully") // Client will automatically reconnect if connection drops result, _ := client2.Tell("square", 7) fmt.Printf("Result: %.0f\n", result.MustFloat64()) } ``` -------------------------------- ### Generate Kite RSA Keys using OpenSSL Source: https://github.com/koding/kite/blob/master/README.md Generates RSA private and public keys required for Kite's security features, specifically for key-based authentication and encryption. These keys are generated using the OpenSSL command-line tool. ```bash openssl genrsa -out key.pem 2048 openssl rsa -in key.pem -pubout > key_pub.pem ``` -------------------------------- ### Go: Custom Error Handling in Kite Source: https://context7.com/koding/kite/llms.txt This Go code snippet demonstrates how to create and return custom errors using the kite.Error type within a Kite server. It handles division by zero and data validation errors, returning specific error types and messages. The client-side code shows how to catch and process these custom kite errors. ```go package main import ( "fmt" "github.com/koding/kite" ) func main() { k := kite.New("errorhandler", "1.0.0") k.HandleFunc("divide", func(r *kite.Request) (interface{}, error) { args := r.Args.MustSliceOfLength(2) a := args[0].MustFloat64() b := args[1].MustFloat64() if b == 0 { // Return custom error return nil, &kite.Error{ Type: "divisionError", Message: "division by zero", } } return a / b, nil }) k.HandleFunc("validate", func(r *kite.Request) (interface{}, error) { var data map[string]interface{} if err := r.Args.One().Unmarshal(&data); err != nil { return nil, &kite.Error{ Type: "validationError", Message: fmt.Sprintf("invalid data format: %s", err), } } if _, ok := data["required_field"]; !ok { return nil, &kite.Error{ Type: "validationError", Message: "required_field is missing", } } return "valid", nil }) k.Config.Port = 9000 go k.Run() <-k.ServerReadyNotify() // Client error handling client := k.NewClient("http://localhost:9000/kite") client.Dial() _, err := client.Tell("divide", 10, 0) if err != nil { if kiteErr, ok := err.(*kite.Error); ok { fmt.Printf("Error type: %s\n", kiteErr.Type) fmt.Printf("Error message: %s\n", kiteErr.Message) } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.