From 2967da1eaefda261375e71e72ad530a2552d6c4c Mon Sep 17 00:00:00 2001 From: Dreamacro Date: Sun, 13 Jun 2021 22:59:46 +0800 Subject: [PATCH] Created use clash as a library (markdown) --- use-clash-as-a-library.md | 54 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 use-clash-as-a-library.md diff --git a/use-clash-as-a-library.md b/use-clash-as-a-library.md new file mode 100644 index 0000000..4158434 --- /dev/null +++ b/use-clash-as-a-library.md @@ -0,0 +1,54 @@ +# Use clash as a library + + +If clash does not fit your own usage, you can use clash as a library. +There is already basic support: + +```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("request incoming from %s to %s\n", metadata.SourceAddress(), metadata.RemoteAddress()) + go func () { + remote, err := direct.DialContext(context.Background(), metadata) + if err != nil { + fmt.Printf("dial error: %s\n", err.Error()) + return + } + relay(remote, conn.Conn()) + }() + } +} + +func relay(l, r net.Conn) { + go io.Copy(l, r) + io.Copy(r, l) +} +```