### Router Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/support-interfaces.md Shows how to use the Router interface to get route information for a given destination. Logs the route's destination and gateway if found. ```go route := router.GetRoute(ctx, "192.168.0.0/16") if route != nil { log.Infof("Route to %s via %s", route.Dst, route.Gateway) } ``` -------------------------------- ### Router Configuration Example Source: https://github.com/go-gost/core/blob/master/_autodocs/chain-and-routing.md Demonstrates how to create a router using a slice of chain.RouterOption functional options. This example shows setting various configurations like chain, resolver, host mapper, timeout, retries, interface, recorders, and logger. ```go opts := []chain.RouterOption{ chain.ChainRouterOption(myChainer), chain.ResolverRouterOption(dnsResolver), chain.HostMapperRouterOption(hostsFile), chain.TimeoutRouterOption(30 * time.Second), chain.RetriesRouterOption(3), chain.InterfaceRouterOption("eth0"), chain.RecordersRouterOption(trafficRecorder), chain.LoggerRouterOption(log), } router := routerFactory.Create(opts...) ``` -------------------------------- ### Per-Service Handler Setup Source: https://github.com/go-gost/core/blob/master/_autodocs/handler.md Demonstrates creating a handler with service-specific options and then accepting and processing connections. ```go // Create handler with service-specific options opts := []handler.Option{ handler.RouterOption(mainRouter), handler.AutherOption(ldapAuth), handler.ServiceOption("my-service"), } h, err := handlerRegistry.Get("http").Create(opts...) if err != nil { log.Fatal(err) } // Accept connections and process them for { conn, err := listener.Accept() if err != nil { log.Fatal(err) } go func(c net.Conn) { defer c.Close() if err := h.Handle(ctx, c); err != nil { log.Warnf("handle error: %v", err) } }(conn) } ``` -------------------------------- ### Listener Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/service-and-listener.md Demonstrates how to create a listener with multiple configuration options applied. ```go opts := []listener.Option{ listener.AddrOption(":8080"), listener.TLSConfigOption(tlsConfig), listener.AutherOption(ldapAuth), listener.AdmissionOption(ipWhitelist), listener.TrafficLimiterOption(bandwidthLim), listener.LoggerOption(log), } listener, err := listenerRegistry.Get("tcp").Create(opts...) ``` -------------------------------- ### Authenticate Method Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/support-interfaces.md Example demonstrating how to use the Authenticate method to validate user credentials. It shows how to handle successful and failed authentication. ```go id, ok := authenticator.Authenticate(ctx, "alice", "secret123", auth.WithService("my-service"), ) if !ok { return fmt.Errorf("authentication failed") } log.Infof("User %s authenticated as %s", "alice", id) ``` -------------------------------- ### Admit Method Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/support-interfaces.md Example demonstrating how to use the Admit method to check if a connection to a given address is allowed. It shows how to use options like WithService and WithNetwork. ```go allowed := admission.Admit(ctx, "tcp", "192.168.1.1:80", admission.WithService("web-service"), admission.WithNetwork("tcp"), ) if !allowed { return fmt.Errorf("connection denied by admission control") } ``` -------------------------------- ### Initialize Router with SockOpts Source: https://github.com/go-gost/core/blob/master/_autodocs/types-and-errors.md Example of creating a router instance with custom socket options, including packet marking. ```go router := chainRouterFactory.Create( chain.SockOptsRouterOption(&chain.SockOpts{ Mark: 123, // Mark packets for policy routing }), ) ``` -------------------------------- ### SelectOptions Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/hop-and-selector.md Demonstrates how to create and use SelectOptions with various option functions to select a node. ```go opts := []hop.SelectOption{ hop.ClientIPSelectOption(net.ParseIP("192.168.1.1")), hop.NetworkSelectOption("tcp"), hop.ProtocolSelectOption("http"), hop.HostSelectOption("api.example.com"), hop.MethodSelectOption("GET"), hop.PathSelectOption("/api/users"), } node := hop.Select(ctx, opts...) ``` -------------------------------- ### Listener Registration Example Source: https://github.com/go-gost/core/blob/master/_autodocs/service-and-listener.md Demonstrates how listener implementations register themselves with a registry using the init() function. ```go // In x/ module func init() { registry.Register(listenerRegistry, "tcp", &TCPListenerFactory{}) registry.Register(listenerRegistry, "tls", &TLSListenerFactory{}) } ``` -------------------------------- ### Connection Limiter Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/support-interfaces.md Example of how to use the connection limiter to check if a connection is allowed and log the maximum connection limit. ```go limiter := connLimiter.Limiter("service:web") if !limiter.Allow(1) { return fmt.Errorf("connection limit exceeded") } log.Infof("Max connections: %d", limiter.Limit()) ``` -------------------------------- ### Node Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/chain-and-routing.md Demonstrates how to create a new Node with specific transport, bypass, and TLS configurations. ```go node := chain.NewNode("proxy1", "proxy.example.com:1080", chain.TransportNodeOption(transporterImpl), chain.BypassNodeOption(bypassRules), chain.TLSNodeOption(&chain.TLSNodeSettings{ ServerName: "proxy.example.com", Secure: true, }), ) ``` -------------------------------- ### Bypass Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/support-interfaces.md Demonstrates how to use the Bypass interface to control network connections. It shows examples for both whitelist and blacklist configurations, and a default direct connection fallback. ```go // Whitelist: only these addresses bypass if bypass.IsWhitelist() && bypass.Contains(ctx, "tcp", "192.168.0.0/16") { return nil // Direct connect, skip proxy } // Blacklist: these addresses go through proxy if !bypass.IsWhitelist() && bypass.Contains(ctx, "tcp", "10.0.0.0/8") { return router.Dial(ctx, "tcp", addr) // Through proxy } // Default: direct connect return dialer.Dial(ctx, "tcp", addr) ``` -------------------------------- ### Route Bind Method Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/chain-and-routing.md Example of using the Route.Bind method to set up a reverse listener through a proxy chain. ```go ln, err := route.Bind(ctx, "tcp", ":9999") ``` -------------------------------- ### Resolver Resolve Method Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/support-interfaces.md Demonstrates how to use the Resolve method to get IP addresses for a given host and network type. Ensure proper error handling. ```go ips, err := resolver.Resolve(ctx, "ip4", "example.com") if err != nil { log.Fatalf("resolve failed: %v", err) } log.Infof("example.com resolves to: %v", ips) ``` -------------------------------- ### Traffic Limiter Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/support-interfaces.md Example demonstrating how to use traffic limiters for inbound and outbound traffic. It shows how to wait for a specific number of bytes and set a bandwidth limit. ```go inLimiter := trafficLimiter.In(ctx, "service:web") outLimiter := trafficLimiter.Out(ctx, "service:web") // Block until n bytes can proceed granted := inLimiter.Wait(ctx, 1024) // Request 1KB log.Infof("Bandwidth limit: %d bytes/sec", inLimiter.Limit()) outLimiter.Set(1024 * 1024) // 1 MB/sec ``` -------------------------------- ### Handler Configuration with Options Source: https://github.com/go-gost/core/blob/master/_autodocs/handler.md Shows an example of creating handler options using various option functions and then using these options to create a handler instance. ```go opts := []handler.Option{ handler.RouterOption(chainRouter), handler.AutherOption(ldapAuth), handler.BypassOption(directConnectRules), handler.TrafficLimiterOption(bandwidthLim), handler.RateLimiterOption(rateLim), handler.RecordersOption(hexRecorder, httpBodyRecorder), handler.ObserverOption(metricsObserver), handler.LoggerOption(log), } h, err := handlerRegistry.Get("http").Create(opts...) ``` -------------------------------- ### Get Handler Factory from Registry Source: https://github.com/go-gost/core/blob/master/_autodocs/metadata-and-utilities.md Example of retrieving a handler factory by its registered name. Returns an error if not found. ```go factory := registry.Get(handlerRegistry, "http") if factory == nil { return fmt.Errorf("handler not found") } ``` -------------------------------- ### Filter Interface Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/hop-and-selector.md Example demonstrating how to use the Filter interface to filter nodes by protocol before applying a selection strategy. ```go // Filter nodes by protocol protocolFilter := &ProtocolFilter{Protocol: "http"} filtered := protocolFilter.Filter(ctx, nodes...) // Only HTTP-capable nodes // Then select from filtered nodes selected := strategy.Apply(ctx, filtered...) ``` -------------------------------- ### Route Dial Method Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/chain-and-routing.md Example of using the Route.Dial method to establish a connection through a proxy chain. ```go conn, err := route.Dial(ctx, "tcp", "example.com:80", chain.InterfaceDialOption("eth0"), ) ``` -------------------------------- ### Observer Observe Method Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/support-interfaces.md Example of how to use the Observe method of the Observer interface to send a batch of events. ```go err := observer.Observe(ctx, []observer.Event{ statsEvent, statusEvent, }) ``` -------------------------------- ### Ingress Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/support-interfaces.md Demonstrates how to use the Ingress interface to set a new routing rule and then query for a rule based on a hostname. ```go rule := &ingress.Rule{ Hostname: "*.api.example.com", Endpoint: "tunnel:api", } ingress.SetRule(ctx, rule) // Query rule found := ingress.GetRule(ctx, "users.api.example.com") if found != nil { log.Infof("Route to tunnel: %s", found.Endpoint) } ``` -------------------------------- ### Record Method Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/support-interfaces.md Demonstrates how to use the Record method with context, a data buffer, and metadata options. Ensure context and necessary options are provided. ```go err := recorder.Record(ctx, buf, recorder.MetadataRecordOption(map[string]any{ "direction": "client->server", "timestamp": time.Now(), }), ) ``` -------------------------------- ### Service Discovery Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/support-interfaces.md Illustrates the usage of the Service Discovery interface for registering a service, discovering services by name, and deregistering a service. ```go service := &sd.Service{ ID: "proxy-1", Name: "proxy", Node: "server1.example.com", Network: "tcp", Address: "server1.example.com:1080", } // Register if err := sd.Register(ctx, service); err != nil { log.Fatal(err) } // Discover services, err := sd.Get(ctx, "proxy") for _, svc := range services { log.Infof("Found: %s at %s", svc.ID, svc.Address) } // Deregister sd.Deregister(ctx, service) ``` -------------------------------- ### Rate Limiter Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/support-interfaces.md Example of using the rate limiter to check if a request is allowed and to log the current rate limit in operations per second. ```go limiter := rateLimiter.Limiter("client:192.168.1.1") if !limiter.Allow(1) { return fmt.Errorf("rate limit exceeded") } log.Infof("Rate limit: %.1f ops/sec", limiter.Limit()) ``` -------------------------------- ### Chainer Route Method Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/chain-and-routing.md Example of using the Chainer.Route method to obtain a Route for a target address. ```go route := chainer.Route(ctx, "tcp", "example.com:443", chain.WithHostRouteOption("example.com"), ) if route == nil { return errors.New("no suitable route") } // Use the route to dial conn, err := route.Dial(ctx, "tcp", "example.com:443") ``` -------------------------------- ### Start Service Source: https://github.com/go-gost/core/blob/master/_autodocs/service-and-listener.md Starts the GOST service in a non-blocking goroutine. Handles potential fatal errors during service operation. ```go go func() { if err := service.Serve(); err != nil { log.Fatalf("service error: %v", err) } }() ``` -------------------------------- ### Set Per-Connection Metadata Source: https://github.com/go-gost/core/blob/master/_autodocs/handler.md Example of setting per-connection metadata using MetadataHandleOption. ```go md := metadata.NewMetadata() md.Set("client.ip", remoteIP) md.Set("client.domain", domain) err := handler.Handle(ctx, conn, handler.MetadataHandleOption(md), ) ``` -------------------------------- ### Metrics Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/support-interfaces.md Demonstrates how to use the Metrics interface to create and update counters, gauges, and observers. Ensure the metrics factory is initialized before use. ```go metrics := metricsFactory.Create() connCounter := metrics.Counter("connections_total", metrics.Labels{ "service": "web", }) connCounter.Inc() activeGauge := metrics.Gauge("connections_active", metrics.Labels{ "service": "web", }) activeGauge.Add(5) activeGauge.Dec() latencyObs := metrics.Observer("request_latency_ms", metrics.Labels{ "endpoint": "/api/users", }) latencyObs.Observe(45.2) ``` -------------------------------- ### Route Nodes Method Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/chain-and-routing.md Example of using the Route.Nodes method to retrieve the list of proxy nodes in a route. ```go nodes := route.Nodes() fmt.Printf("Route has %d hops\n", len(nodes)) for i, node := range nodes { fmt.Printf(" Hop %d: %s (%s)\n", i+1, node.Name, node.Addr) } ``` -------------------------------- ### Retrieve All Registered Handlers Source: https://github.com/go-gost/core/blob/master/_autodocs/metadata-and-utilities.md Example of fetching all registered handler factories from the registry and iterating through them. ```go all := registry.GetAll(handlerRegistry) for name, factory := range all { log.Printf("Handler: %s → %T", name, factory) } ``` -------------------------------- ### Binder Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/dialer-and-connector.md Demonstrates how to check if a connector implements the Binder interface and use its Bind method to create a listener for reverse tunnels. ```go var be Binder if !errors.As(connector, &be) { return fmt.Errorf("connector does not support bind") } ln, err := be.Bind(ctx, conn, "tcp", ":9999") ``` -------------------------------- ### Matcher Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/support-interfaces.md Demonstrates how to create a Request object and use a Matcher to determine if it matches a routing rule. Ensure the Matcher is properly initialized before use. ```go req := &routing.Request{ ClientIP: net.ParseIP("192.168.1.1"), Host: "api.example.com", Method: "POST", Path: "/v1/users", } if matcher.Match(req) { log.Println("Request matches routing rule") } ``` -------------------------------- ### Selector Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/hop-and-selector.md Illustrates how to use the generic selector to pick a single node from a list of nodes. ```go nodes := []*chain.Node{node1, node2, node3} selected := selector.Select(ctx, nodes...) // Returns one node ``` -------------------------------- ### Select Method Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/hop-and-selector.md Demonstrates how to use the Select method of the Hop interface to pick a node based on selection options. Ensure to handle the case where no node is available. ```go node := hop.Select(ctx, hop.HostSelectOption("example.com"), hop.MethodSelectOption("GET"), hop.ProtocolSelectOption("http"), ) if node == nil { return errors.New("no available nodes") } // Use node.Options().Transport to dial through this node ``` -------------------------------- ### Stats Interface Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/support-interfaces.md Demonstrates how to use the Stats interface to increment counters, retrieve values, check for updates, and reset statistics. ```go stats.Add(stats.KindTotalConns, 1) // Increment total connections stats.Add(stats.KindInputBytes, 1024) // Add input bytes current := stats.Get(stats.KindCurrentConns) log.Infof("Current connections: %d", current) if stats.IsUpdated() { log.Infof("Stats: %+v", statsSnapshot) stats.Reset() } ``` -------------------------------- ### NodeList Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/hop-and-selector.md Demonstrates how to check if a hop implements the NodeList interface and iterate through its nodes to display failure counts. ```go if nl, ok := hop.(NodeList); ok { nodes := nl.Nodes() fmt.Printf("Hop has %d nodes:\n", len(nodes)) for _, node := range nodes { count := node.Marker().Count() if count > 0 { fmt.Printf(" %s: %d failures\n", node.Name, count) } } } ``` -------------------------------- ### Register Components in Handler Registry Source: https://github.com/go-gost/core/blob/master/_autodocs/metadata-and-utilities.md Example of registering HTTP and SOCKS5 handler factories into the `handlerRegistry` during module initialization. ```go // In x/ module init() func init() { registry.Register(handlerRegistry, "http", &HTTPHandlerFactory{}) registry.Register(handlerRegistry, "socks5", &SOCKS5HandlerFactory{}) } ``` -------------------------------- ### Marker Interface Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/hop-and-selector.md Demonstrates how to use the Marker interface to mark nodes as failed, check failure counts and times, and reset failure states. ```go // Mark a node as failed node.Marker().Mark() // Check failure state if node.Marker().Count() > 3 { log.Warnf("Node %s has %d failures", node.Name, node.Marker().Count()) } // Check when it last failed lastFailure := node.Marker().Time() if time.Since(lastFailure) > 5*time.Minute { // Try node again, it's been long enough node.Marker().Reset() } // Example: Selector skips nodes with too many recent failures for _, node := range nodes { marker := node.Marker() if marker.Count() > 0 { lastFail := marker.Time() if time.Since(lastFail) < 1*time.Minute { continue // Skip, still in failure period } } // This node is eligible selected = node break } ``` -------------------------------- ### LoggerGroup Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/support-interfaces.md Shows how to create a LoggerGroup to fan-out log messages to multiple logger backends, such as a file logger and a standard output logger. ```go group := logger.LoggerGroup(fileLogger, stdoutLogger) group.Info("Message sent to both loggers") ``` -------------------------------- ### Logger Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/support-interfaces.md Demonstrates how to obtain a default logger, add fields for context, and log messages at different levels. Use IsLevelEnabled to check if a level is active before logging. ```go logger := logger.Default() log := logger.WithFields(map[string]any{ "service": "web", "addr": "192.168.1.1:8080", }) log.Info("Connection accepted") log.Infof("Processing request from %s", addr) log.Warn("Slow connection") log.Error("Failed to route") if log.IsLevelEnabled(logger.DebugLevel) { log.Debugf("Debug info: %+v", data) } ``` -------------------------------- ### Buffer Pool Usage Pattern Source: https://github.com/go-gost/core/blob/master/_autodocs/metadata-and-utilities.md Demonstrates the recommended usage pattern for the buffer pool, ensuring every Get is paired with a Put, typically using defer. ```go // Always pair Get with Put (using defer) buf := bufpool.Get(1024) deferr bufpool.Put(buf) // Now use buf safely n, err := conn.Read(buf) // ... ``` -------------------------------- ### Forwarder Interface Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/handler.md Demonstrates how to check if a handler implements the Forwarder interface and use its Forward method to change the destination hop at runtime. ```go if fwd, ok := handler.(Forwarder); ok { fwd.Forward(destinationHop) } ``` -------------------------------- ### HostMapper Lookup Method Usage Example Source: https://github.com/go-gost/core/blob/master/_autodocs/support-interfaces.md Shows how to use the Lookup method to find a static IP mapping for a hostname. If no mapping is found, it suggests falling back to DNS resolution. ```go ips, found := hostMapper.Lookup(ctx, "ip", "internal.example.com") if found { log.Infof("Mapping found: %v", ips) return ips } // Fall back to DNS resolution return resolver.Resolve(ctx, "ip", host) ``` -------------------------------- ### Custom Handler Implementation Source: https://github.com/go-gost/core/blob/master/_autodocs/implementation-guide.md Implement the handler.Handler interface to create a custom handler. This example shows how to initialize, authenticate, admit, parse requests, and forward traffic. ```go package myhandler import ( "context" "net" "github.com/go-gost/core/handler" "github.com/go-gost/core/metadata" ) type MyHandler struct { options handler.Options } // Init initializes from metadata func (h *MyHandler) Init(md metadata.Metadata) error { // Parse metadata and populate h.options if md.IsExists("custom.field") { // Configure from metadata } return nil } // Handle processes an inbound connection func (h *MyHandler) Handle(ctx context.Context, conn net.Conn, opts ...handler.HandleOption) error { defer conn.Close() // Parse handle options var handleOpts handler.HandleOptions for _, opt := range opts { opt(&handleOpts) } // Authenticate if h.options.Auther != nil { user, password, ok := parseCredentials(conn) if !ok { return fmt.Errorf("authentication required") } id, ok := h.options.Auther.Authenticate(ctx, user, password) if !ok { return fmt.Errorf("authentication failed") } // Track authenticated user handleOpts.Metadata.Set("auth.user", id) } // Check admission if h.options.Admission != nil { clientAddr := conn.RemoteAddr().String() if !h.options.Admission.Admit(ctx, "tcp", clientAddr) { return fmt.Errorf("connection denied") } } // Parse request and route through chain req, err := parseRequest(conn) if err != nil { return err } // Route through proxy chain destConn, err := h.options.Router.Dial(ctx, "tcp", req.Host) if err != nil { h.options.Logger.Errorf("Dial failed: %v", err) return err } defer destConn.Close() // Forward traffic return forwardTraffic(conn, destConn) } ``` -------------------------------- ### Store Request Context Metadata Source: https://github.com/go-gost/core/blob/master/_autodocs/metadata-and-utilities.md Illustrates how to store per-request metadata, such as request ID, client IP, and start time, and pass it to a handler. ```go // Per-request metadata md := metadata.NewMetadata() md.Set("request.id", requestID) md.Set("client.ip", clientIP) md.Set("start.time", time.Now()) // Pass to handler handler.Handle(ctx, conn, handler.MetadataHandleOption(md)) // Handler can retrieve reqID := md.Get("request.id") ``` -------------------------------- ### Request-Based Routing with Select Options Source: https://github.com/go-gost/core/blob/master/_autodocs/hop-and-selector.md Demonstrates routing logic based on request attributes like hostname, path, and method. Different hops can be selected based on conditions, and specific select options are used to guide the node selection process. ```go // Route based on hostname if host == "api.example.com" { hop = apiHop // Use API-specific nodes } else if host == "static.example.com" { hop = cdnHop // Use CDN nodes } node := hop.Select(ctx, hop.HostSelectOption(host), hop.PathSelectOption(path), hop.MethodSelectOption(method), ) ``` -------------------------------- ### Initialize Component from Config Source: https://github.com/go-gost/core/blob/master/_autodocs/metadata-and-utilities.md Demonstrates the process of creating and initializing a component using configuration data and a metadata store. ```go // 1. Create empty metadata store md := metadata.NewMetadata() // 2. Populate from config file md.Set("listen", ":8080") md.Set("tls.cert", "/path/to/cert.pem") md.Set("auth.service", "ldap") // 3. Get factory from registry factory := registry.Get(handlerRegistry, "http") // 4. Create component via factory handler, err := factory.Create(opts...) // opts come from config // 5. Initialize with metadata if err := handler.Init(md); err != nil { log.Fatal(err) } ``` -------------------------------- ### Creating a Listener from Configuration Source: https://github.com/go-gost/core/blob/master/_autodocs/service-and-listener.md Shows how to create a listener instance using configuration options like address and TLS settings. ```go md := metadata.NewMetadata() md.Set("listen", ":8080") md.Set("tls.cert", "/path/to/cert.pem") opts := []listener.Option{ listener.AddrOption(":8080"), listener.TLSConfigOption(tlsConfig), } factory := listenerRegistry.Get("tcp") ln, err := factory.Create(opts...) ln.Init(md) ``` -------------------------------- ### Metadata Interface for Configuration Source: https://github.com/go-gost/core/blob/master/_autodocs/overview.md Illustrates the Metadata interface used for storing configuration options that do not map to explicit struct fields. Usage involves setting and getting values by key. ```go type Metadata interface { IsExists(key string) bool Set(key string, value any) Get(key string) any } // Usage node.Metadata().Set("custom.option", "value") ``` -------------------------------- ### Integration Test for Proxy Chain Source: https://github.com/go-gost/core/blob/master/_autodocs/implementation-guide.md An example of integration testing for the proxy chain, demonstrating the creation of real components and testing their interactions. This verifies the end-to-end functionality of the chain. ```go // Test actual component interactions func TestProxyChain(t *testing.T) { // Create real components nodes := []*chain.Node{ chain.NewNode("test", "localhost:9999", chain.TransportNodeOption(socks5Transporter), ), } hop := hopFactory.Create(hop.NodesOption(nodes)) route := routeFactory.Create(route.HopOption(hop)) chainer := chainFactory.Create(chainer.RouteOption("test", route)) router := routerFactory.Create( chain.ChainRouterOption(chainer), chain.TimeoutRouterOption(5 * time.Second), ) // Test dial through chain conn, err := router.Dial(context.Background(), "tcp", "example.com:80") if err != nil { t.Fatalf("dial failed: %v", err) } defer conn.Close() // Verify connection works if _, err := conn.Write([]byte("test")); err != nil { t.Fatalf("write failed: %v", err) } } ``` -------------------------------- ### Setting Up a Multi-Hop Proxy Chain in Go Source: https://github.com/go-gost/core/blob/master/_autodocs/implementation-guide.md Demonstrates creating a multi-hop proxy chain with load balancing. Ensure the necessary transport, hop, route, and chain factories are initialized. ```go nodes := []*chain.Node{ chain.NewNode("proxy1", "proxy1.example.com:1080", chain.TransportNodeOption(socks5Transport), chain.PriorityNodeOption(1), ), chain.NewNode("proxy2", "proxy2.example.com:1080", chain.TransportNodeOption(socks5Transport), chain.PriorityNodeOption(2), ), } // Create hop for load balancing hop := hopFactory.Create( hop.SelectionStrategy("round-robin"), hop.NodesOption(nodes), ) // Create route through nodes route := routeFactory.Create( route.HopOption(hop), route.LoggerOption(log), ) // Create chainer that selects routes by name chainer := chainFactory.Create( chainer.RouteOption("chain1", route), ) // Use in router router := routerFactory.Create( chain.ChainRouterOption(chainer), ) ``` -------------------------------- ### Setting Up a Basic Proxy Service in Go Source: https://github.com/go-gost/core/blob/master/_autodocs/implementation-guide.md This snippet demonstrates how to create a basic proxy service using Go Gost. It covers setting up a logger, chain router, listener, handler, and the service itself. Ensure all necessary registries (chainRouterFactory, listenerRegistry, handlerRegistry) and configurations are available. ```go package main import ( "context" "log" "github.com/go-gost/core/chain" "github.com/go-gost/core/handler" "github.com/go-gost/core/listener" "github.com/go-gost/core/logger" "github.com/go-gost/core/registry" "github.com/go-gost/core/service" ) func main() { ctx := context.Background() // 1. Create logger log := logger.Default() // 2. Create chain router (connects through proxy chain) router := chainRouterFactory.Create( chain.ChainRouterOption(myChainer), chain.TimeoutRouterOption(30 * time.Second), chain.LoggerRouterOption(log), ) // 3. Create listener (accepts inbound connections) listenerOpts := []listener.Option{ listener.AddrOption(":8080"), listener.RouterOption(router), listener.LoggerOption(log), } ln, err := listenerRegistry.Get("tcp").Create(listenerOpts...) if err != nil { log.Fatalf("listener creation failed: %v", err) } // 4. Create handler (processes connections) handlerOpts := []handler.Option{ handler.RouterOption(router), handler.LoggerOption(log), } h, err := handlerRegistry.Get("http").Create(handlerOpts...) if err != nil { log.Fatalf("handler creation failed: %v", err) } // 5. Create service (combines listener and handler) svc, err := serviceFactory.Create( listener: ln, handler: h, ) if err != nil { log.Fatalf("service creation failed: %v", err) } // 6. Run service log.Infof("Service listening on %s", svc.Addr()) if err := svc.Serve(); err != nil { log.Fatalf("service error: %v", err) } } ``` -------------------------------- ### Initialize Listener with Metadata Source: https://github.com/go-gost/core/blob/master/_autodocs/service-and-listener.md Initializes a listener using a metadata configuration. Use this to set listen address and TLS options. ```go md := metadata.NewMetadata() md.Set("listen", ":8080") md.Set("tls", true) if err := listener.Init(md); err != nil { log.Fatal(err) } ``` -------------------------------- ### Unregister a Handler Source: https://github.com/go-gost/core/blob/master/_autodocs/metadata-and-utilities.md Example of removing a handler factory from the registry using its registered name. ```go registry.Unregister(handlerRegistry, "deprecated_handler") ``` -------------------------------- ### Use Metadata for Dynamic Configuration Source: https://github.com/go-gost/core/blob/master/_autodocs/metadata-and-utilities.md Shows how to store and retrieve dynamic configuration values using a metadata store. ```go // Store dynamic configuration node.Metadata().Set("priority", 10) node.Metadata().Set("weight", 2) node.Metadata().Set("max_conns", 100) // Read in selector priority := node.Metadata().Get("priority").(int) weight := node.Metadata().Get("weight").(int) ``` -------------------------------- ### Initialize Connector Source: https://github.com/go-gost/core/blob/master/_autodocs/dialer-and-connector.md Initializes the connector with provided metadata. Ensure metadata is correctly formatted before calling Init. ```go md := metadata.NewMetadata() if err := connector.Init(md); err != nil { log.Fatal(err) } ``` -------------------------------- ### Get and Assert Metadata Value Source: https://github.com/go-gost/core/blob/master/_autodocs/types-and-errors.md Retrieves a metadata value by key and asserts its type to time.Duration. ```go // Get metadata value with type assertion value := node.Metadata().Get("timeout") if value != nil { timeout, ok := value.(time.Duration) if ok { log.Printf("Timeout: %v", timeout) } } ``` -------------------------------- ### Get Listener Address Source: https://github.com/go-gost/core/blob/master/_autodocs/service-and-listener.md Retrieves the network address the listener is bound to. Useful for logging or configuration. ```go fmt.Printf("Listening on %v\n", listener.Addr()) ``` -------------------------------- ### Check if Handler is Registered Source: https://github.com/go-gost/core/blob/master/_autodocs/metadata-and-utilities.md Example of checking if a specific handler, like the HTTP handler, is available in the registry. ```go if registry.IsRegistered(handlerRegistry, "http") { log.Println("HTTP handler is available") } ``` -------------------------------- ### SOCKS5 Connector Implementation Outline Source: https://github.com/go-gost/core/blob/master/_autodocs/dialer-and-connector.md Illustrates the steps required to implement a SOCKS5 connector, including sending CONNECT requests and optionally supporting BIND and Handshaker interfaces. ```go 1. Implement `Connector` with `Connect` method 2. In `Connect`: - Send SOCKS5 CONNECT request: `0x05 0x01 0x00 host:port` - Receive CONNECT response - Return wrapped connection to destination 3. Optionally implement `Binder` for SOCKS5 BIND command 4. Optionally implement `Handshaker` for SOCKS5 greeting ``` -------------------------------- ### Get Service Address Source: https://github.com/go-gost/core/blob/master/_autodocs/service-and-listener.md Retrieves the network address the service is currently listening on. Useful for monitoring or configuration. ```go addr := service.Addr() fmt.Printf("Service listening on %v\n", addr) ``` -------------------------------- ### Handling BindError Source: https://github.com/go-gost/core/blob/master/_autodocs/service-and-listener.md Example of checking for and handling BindError after a bind operation. It logs a warning for transient bind errors. ```go ln, err := route.Bind(ctx, "tcp", ":9999") if err != nil { var be *listener.BindError if errors.As(err, &be) { log.Warn("Transient bind error, retrying...") } } ``` -------------------------------- ### Handling AcceptError Source: https://github.com/go-gost/core/blob/master/_autodocs/service-and-listener.md Example of how to check for and handle AcceptError during listener acceptance. It logs a warning and continues on transient errors. ```go conn, err := listener.Accept() if err != nil { var ae *listener.AcceptError if errors.As(err, &ae) { log.Warn("Transient accept error, retrying...") continue } } ``` -------------------------------- ### Setting Up a Chain Router Source: https://github.com/go-gost/core/blob/master/_autodocs/chain-and-routing.md Configure a chain router by creating nodes, specifying a chainer implementation, and setting router options like timeout and retries. Use the router to establish connections. ```go // Create nodes nodes := []*chain.Node{ chain.NewNode("proxy1", "proxy1.example.com:1080", chain.TransportNodeOption(socks5Transport), ), chain.NewNode("proxy2", "proxy2.example.com:1080", chain.TransportNodeOption(socks5Transport), ), } // Create chainer (selects routes) chainer := myChainerImpl // implements chain.Chainer // Create router router := routerFactory.Create( chain.ChainRouterOption(chainer), chain.TimeoutRouterOption(30 * time.Second), chain.RetriesRouterOption(3), ) // Use router to dial conn, err := router.Dial(ctx, "tcp", "example.com:80") ``` -------------------------------- ### Accept Loop Implementation Source: https://github.com/go-gost/core/blob/master/_autodocs/service-and-listener.md Illustrates the main accept loop for a listener, handling incoming connections and errors, including graceful shutdown on ErrClosed. ```go for { conn, err := listener.Accept() if err != nil { if errors.Is(err, listener.ErrClosed) { break } log.Warnf("accept error: %v", err) continue } go handler.Handle(ctx, conn) } listener.Close() ``` -------------------------------- ### Get Source: https://github.com/go-gost/core/blob/master/_autodocs/metadata-and-utilities.md Returns the value registered under the specified name. If no value is registered, it returns the zero value of type T. ```APIDOC ## Get ### Description Returns the value registered under the specified name. If no value is registered, it returns the zero value of type T. ### Method ``` Get(name string) T ``` ### Usage Example ```go factory := registry.Get(handlerRegistry, "http") if factory == nil { return fmt.Errorf("handler not found") } ``` ``` -------------------------------- ### Bind Method Signature Source: https://github.com/go-gost/core/blob/master/_autodocs/chain-and-routing.md Sets up a reverse listener through the proxy node. Allows incoming connections to be proxied back through the chain. ```go Bind(ctx context.Context, conn net.Conn, network, address string, opts ...connector.BindOption) (net.Listener, error) ``` -------------------------------- ### Get Router Options Source: https://github.com/go-gost/core/blob/master/_autodocs/chain-and-routing.md Retrieves the router's configuration options. Useful for inspecting settings like retries and timeouts. ```go routerOpts := router.Options() fmt.Printf("Retries: %d, Timeout: %v\n", routerOpts.Retries, routerOpts.Timeout) ``` -------------------------------- ### router.Router Source: https://github.com/go-gost/core/blob/master/CLAUDE.md Interface for querying the OS-level route table in TUN mode. It provides a method to get the route for a given destination. ```APIDOC ## router.Router ### Description Interface for querying the OS-level route table in TUN mode. ### Method Signature `GetRoute(ctx context.Context, dst string) (string, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response - **string** (string) - The route information for the destination. - **error** (error) - An error if retrieving the route fails. ### Request Example None ### Response Example None ``` -------------------------------- ### Create Service from Configuration Source: https://github.com/go-gost/core/blob/master/_autodocs/implementation-guide.md Function to create a service instance by parsing a ServiceConfig struct. It initializes the listener, handler, and router based on the provided configuration. ```go // Parse and create service func CreateServiceFromConfig(cfg ServiceConfig) (service.Service, error) { // 1. Parse listener md := metadata.NewMetadata() md.Set("listen", cfg.Listener.Address) listenerFactory := registry.Get(listenerRegistry, cfg.Listener.Type) ln := listenerFactory.Create() ln.Init(md) // 2. Parse handler handlerFactory := registry.Get(handlerRegistry, cfg.Handler.Type) h := handlerFactory.Create() // 3. Parse router timeout, _ := time.ParseDuration(cfg.Router.Timeout) router := routerFactory.Create( chain.TimeoutRouterOption(timeout), chain.RetriesRouterOption(cfg.Router.Retries), ) // 4. Combine into service svc, _ := serviceFactory.Create(listener: ln, handler: h) return svc, nil } ``` -------------------------------- ### ingress.Ingress Source: https://github.com/go-gost/core/blob/master/CLAUDE.md Interface for managing ingress rules, mapping hostnames to tunnel endpoints. Provides methods to set and get rules. ```APIDOC ## ingress.Ingress ### Description Interface for managing ingress rules, mapping hostnames to tunnel endpoints. ### Method Signatures - `SetRule(host string, endpoint string) error` - `GetRule(host string) (endpoint string, ok bool)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (SetRule) - **error** (error) - An error if setting the rule fails. #### Success Response (GetRule) - **endpoint** (string) - The tunnel endpoint for the host. - **ok** (bool) - True if a rule was found for the host, false otherwise. ### Request Example None ### Response Example None ``` -------------------------------- ### Forward Proxy Request Path Source: https://github.com/go-gost/core/blob/master/README.md Illustrates the flow of a request in a forward proxy setup, from client connection acceptance to destination. ```text Client │ ▼ ┌──────────────┐ │ Listener │ Accepts inbound connections │ │ (tcp, tls, ws, http2/3, quic, kcp, icmp, tun, udp, ...) └──────┬───────┘ │ net.Conn ▼ ┌──────────────┐ │ Handler │ Authenticates, routes, and proxies traffic │ │ (http, socks4/5, ss, ssh, tunnel, tun, dns, redirect, ...) └──────┬───────┘ │ chain.Router.Dial(ctx, network, address) ▼ ┌──────────────────────────────────────────────────────────────┐ │ chain.Router │ │ │ │ Resolver ─► HostMapper ─► Recorders ─► Retries/Timeout │ │ │ │ │ ▼ │ │ ┌─────────┐ ┌─────┐ ┌──────────┐ │ │ │ Chainer │──►│ Hop │──►│ Node[] │ (per chain hop) │ │ └─────────┘ └──┬──┘ └────┬─────┘ │ │ │ │ │ │ Selector chain.Transporter │ │ (rr/random/ ┌──────────────────┐ │ │ weighted/ │ Dialer │ dial to next │ │ fail-filter) │ Handshaker │ proxy hop │ │ │ Connector │ connect to │ │ │ Binder │ destination │ │ │ Multiplexer │ │ │ └──────────────────┘ │ └──────────────────────────────────────────────────────────────┘ │ ▼ Destination ``` -------------------------------- ### Option Function Pattern for Configuration Source: https://github.com/go-gost/core/blob/master/_autodocs/quick-reference.md Demonstrates the pattern for using option functions to configure a struct. This pattern is useful for providing flexible initialization for components. ```go // Options struct type Options struct { Field1 string Field2 int Field3 interface{} } // Option function type type Option func(*Options) // Option constructors func Field1Option(v string) Option { return func(opts *Options) { opts.Field1 = v } } func Field2Option(v int) Option { return func(opts *Options) { opts.Field2 = v } } // Usage opts := []Option{ Field1Option("value"), Field2Option(42), } component := factory.Create(opts...) ``` -------------------------------- ### Functional Options for Component Initialization Source: https://github.com/go-gost/core/blob/master/_autodocs/overview.md Demonstrates the functional options pattern for configuring components at initialization time. Options are passed as functions that modify a configuration struct. ```go type Options struct { ... } type Option func(*Options) type DialOptions struct { ... } type DialOption func(*DialOptions) // Usage myDial(ctx, addr, dialer.HostDialOption("example.com")) ``` -------------------------------- ### SelectOptions Structure Source: https://github.com/go-gost/core/blob/master/_autodocs/types-and-errors.md Runtime context for node selection, capturing client IP, network, address, protocol, host, HTTP method/path/query/headers. ```go type SelectOptions struct { ClientIP net.IP // Client IP address Network string // Connection network type Addr string // Destination address Protocol string // Proxy protocol Host string // Target hostname Method string // HTTP request method Path string // HTTP request path Query url.Values // HTTP query parameters Header http.Header // HTTP request headers } ``` -------------------------------- ### Handle Dial Errors Source: https://github.com/go-gost/core/blob/master/_autodocs/chain-and-routing.md Provides an example of how to handle errors during the Dial operation, specifically checking for context deadline exceeded or cancellation. ```go conn, err := router.Dial(ctx, "tcp", "example.com:443") if err != nil { if errors.Is(ctx.Err(), context.DeadlineExceeded) { log.Warn("dial timeout") } else if errors.Is(ctx.Err(), context.Canceled) { log.Warn("dial cancelled") } else { log.Fatalf("dial error: %v", err) } } ``` -------------------------------- ### Initialize Dialer with Metadata Source: https://github.com/go-gost/core/blob/master/_autodocs/dialer-and-connector.md Initializes the dialer with metadata configuration, such as timeouts. Ensure Init is called once during dialer construction. ```go md := metadata.NewMetadata() md.Set("timeout", "10s") if err := dialer.Init(md); err != nil { log.Fatal(err) } ``` -------------------------------- ### Listener Interface Methods Source: https://github.com/go-gost/core/blob/master/_autodocs/service-and-listener.md This section details the methods available on the Listener interface, including their purpose, parameters, return values, and usage examples. ```APIDOC ## Listener Interface Methods ### Init Initializes the listener with metadata configuration. ### Method `Init(metadata.Metadata) error` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go md := metadata.NewMetadata() md.Set("listen", ":8080") md.Set("tls", true) if err := listener.Init(md); err != nil { log.Fatal(err) } ``` ### Response #### Success Response (0) No explicit success response defined, returns nil on success. #### Response Example None --- ### Accept Blocks and returns the next inbound connection. ### Method `Accept() (net.Conn, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go conn, err := listener.Accept() if err != nil { if errors.Is(err, listener.ErrClosed) { return // Listener is closed, stop accepting } var ae *listener.AcceptError if errors.As(err, &ae) { // Temporary accept error, retry log.Warnf("accept error (will retry): %v", err) continue } } ``` ### Response #### Success Response (0) Returns `net.Conn` representing the accepted connection. #### Response Example None --- ### Addr Returns the listener's bind address. ### Method `Addr() net.Addr` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go fmt.Printf("Listening on %v\n", listener.Addr()) ``` ### Response #### Success Response (0) Returns `net.Addr` of the listener. #### Response Example None --- ### Close Stops the listener and releases resources. ### Method `Close() error` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go defer listener.Close() ``` ### Response #### Success Response (0) Returns `nil` on success. #### Response Example None ``` -------------------------------- ### bufpool Source: https://github.com/go-gost/core/blob/master/CLAUDE.md Provides a tiered sync.Pool for byte buffers, ranging from 128 bytes to 64KB. Offers Get and Put methods for buffer management. ```APIDOC ## bufpool ### Description Provides a tiered sync.Pool for byte buffers. ### Method Signatures - `Get(size int) []byte` - `Put(b []byte)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (Get) - **[]byte** (slice of bytes) - A byte buffer of the requested size. ### Request Example None ### Response Example None ``` -------------------------------- ### Component Initialization Interface Source: https://github.com/go-gost/core/blob/master/_autodocs/overview.md Defines the standard interface for component initialization, accepting metadata for configuration. This pattern centralizes configuration parsing. ```go type SomeComponent interface { Init(metadata.Metadata) error // ... other methods } ``` -------------------------------- ### Reverse Proxy / Tunnel Request Path Source: https://github.com/go-gost/core/blob/master/README.md Details the request flow for a reverse proxy or tunnel setup, showing how clients connect through to a destination. ```text Client ◄── Tunnel ──┐ │ ┌─────▼──────┐ │ Listener │ └─────┬──────┘ │ ┌─────▼──────┐ │ Handler │ └─────┬──────┘ │ chain.Router.Bind(ctx, network, address) ▼ chain.Router ─► chain.Route.Bind() ─► Transporter.Bind() │ │ ▼ ▼ Destination net.Listener (on remote node) ``` -------------------------------- ### HTTP Connector Implementation Outline Source: https://github.com/go-gost/core/blob/master/_autodocs/dialer-and-connector.md Outlines the implementation of an HTTP connector, focusing on sending HTTP CONNECT requests for tunneling and noting the typical absence of Binder implementation. ```go 1. Implement `Connector` with `Connect` method 2. In `Connect`: - Send HTTP CONNECT request: `CONNECT host:port HTTP/1.1` - Receive HTTP response (200 OK) - Return wrapped connection for tunneling 3. Typically does NOT implement `Binder` (HTTP CONNECT doesn't support reverse tunnels) ``` -------------------------------- ### Registering and Retrieving Components Source: https://github.com/go-gost/core/blob/master/_autodocs/overview.md Shows how component types are registered with a generic registry using a factory function. Components can then be retrieved by name. ```go registry.Register("handler", "http", httpHandlerFactory) handler := registry.Get("http") // returns zero value if not found allHandlers := registry.GetAll() // map[string]HandlerFactory ```