Advanced Usage · Clash documentation

Integrating Clash into a Golang Program

When handling proxy connections in a Go program, read metadata from the Clash SOCKS listener and ConnContext, then connect the Direct outbound, DialContext, and relay for bidirectional forwarding.

  • Golang
  • ConnContext
  • SourceAddress
  • DialContext
  • relay
Advanced Usage

Scope of this historical document

This document preserves historical instructions for original Clash / Clash Premium to help interpret older configurations. References to “Premium only”, unsupported features, or platform limits do not describe current Mihomo capabilities. Do not use them to overwrite your current client configuration or run permission-related commands.

For Mihomo, consult current Mihomo configuration documentation. For the graphical interface, installation, and permissions, follow the documentation for your specific client.

If Clash does not meet your needs, you can use Clash in your own Golang code.

Basic support is currently available:

go
package main

import (
	"context"
	"fmt"
	"io"
	"net"

	"github.com/Dreamacro/clash/adapter/outbound"
	"github.com/Dreamacro/clash/constant"
	"github.com/Dreamacro/clash/listener/socks"
)

func main() {
	in := make(chan constant.ConnContext, 100)
	defer close(in)

	l, err := socks.New("127.0.0.1:10000", in)
	if err != nil {
		panic(err)
	}
	defer l.Close()

	println("listen at:", l.Address())

	direct := outbound.NewDirect()

	for c := range in {
		conn := c
		metadata := conn.Metadata()
		fmt.Printf("请求从 %s 传入到 %s\n", metadata.SourceAddress(), metadata.RemoteAddress())
		go func () {
			remote, err := direct.DialContext(context.Background(), metadata)
			if err != nil {
				fmt.Printf("Dial 错误: %s\n", err.Error())
				return
			}
			relay(remote, conn.Conn())
		}()
	}
}

func relay(l, r net.Conn) {
	go io.Copy(l, r)
	io.Copy(r, l)
}