github.com/igoogolx/clash@v1.19.8/docs/zh_CN/advanced-usages/golang-api.md (about)

     1  ---
     2  sidebarTitle: 在 Golang 程序中集成 Clash
     3  sidebarOrder: 3
     4  ---
     5  
     6  # 在 Golang 程序中集成 Clash
     7  
     8  如果 Clash 不能满足您的需求, 您可以在自己的 Golang 代码中使用 Clash.
     9  
    10  目前已经有基本的支持:
    11  
    12  ```go
    13  package main
    14  
    15  import (
    16  	"context"
    17  	"fmt"
    18  	"io"
    19  	"net"
    20  
    21  	"github.com/Dreamacro/clash/adapter/outbound"
    22  	"github.com/Dreamacro/clash/constant"
    23  	"github.com/Dreamacro/clash/listener/socks"
    24  )
    25  
    26  func main() {
    27  	in := make(chan constant.ConnContext, 100)
    28  	defer close(in)
    29  
    30  	l, err := socks.New("127.0.0.1:10000", in)
    31  	if err != nil {
    32  		panic(err)
    33  	}
    34  	defer l.Close()
    35  
    36  	println("listen at:", l.Address())
    37  
    38  	direct := outbound.NewDirect()
    39  
    40  	for c := range in {
    41  		conn := c
    42  		metadata := conn.Metadata()
    43  		fmt.Printf("请求从 %s 传入到 %s\n", metadata.SourceAddress(), metadata.RemoteAddress())
    44  		go func () {
    45  			remote, err := direct.DialContext(context.Background(), metadata)
    46  			if err != nil {
    47  				fmt.Printf("Dial 错误: %s\n", err.Error())
    48  				return
    49  			}
    50  			relay(remote, conn.Conn())
    51  		}()
    52  	}
    53  }
    54  
    55  func relay(l, r net.Conn) {
    56  	go io.Copy(l, r)
    57  	io.Copy(r, l)
    58  }
    59  ```