本指南将引导您完成设置 Go 环境并在 Go 代码中使用 Outline SDK 的流程。
我们将构建一个名为 splitfetch
的示例应用,以展示该 SDK 的一项功能。此应用会提取网页,但不会在单个网络数据包中发送请求,而是使用 Outline SDK 将初始 TCP 流拆分为两个单独的数据包。这可能有助于绕过某些形式的网络干预。
您将能够在 Linux、Mac 和 Windows 上运行该应用。如需与移动应用集成,请参阅将 Outline SDK 添加到移动应用。
第 1 步:设置 Go
首先,您需要 Go 编程语言。如果您已安装 Go(1.21 或更高版本),则可以跳至下一步。
如需安装,您可以按照官方指南操作;如果您使用软件包管理器,请执行以下操作:
安装 Go 后,您可以在终端中运行以下命令,验证其是否已正确安装:
go version
第 2 步:创建 splitfetch
应用
我们来设置 splitfetch
项目。首先,创建项目目录并初始化 Go 模块:
mkdir splitfetch
cd splitfetch
go mod init example/splitfetch
接下来,拉入 Outline SDK 并创建 main.go
文件:
go get github.com/Jigsaw-Code/outline-sdk@latest
touch main.go
第 3 步:在应用中使用 Outline SDK
在您喜爱的代码编辑器中打开 main.go
文件,然后将以下代码粘贴到其中。此代码包含 splitfetch
应用的所有逻辑。
package main
import (
"context"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"github.com/Jigsaw-Code/outline-sdk/transport"
"github.com/Jigsaw-Code/outline-sdk/transport/split"
)
// The number of bytes to send in the first packet.
const splitPacketSize = 3
func main() {
// 1. Get the URL from the command-line arguments.
if len(os.Args) < 2 {
log.Fatalf("Usage: %s <URL>", os.Args[0])
}
url := os.Args[1]
// 2. Create a split dialer from the Outline SDK.
// This dialer wraps a standard TCP dialer to add the splitting behavior.
dialer, err := split.NewStreamDialer(&transport.TCPDialer{}, split.NewFixedSplitIterator(splitPacketSize))
if err != nil {
log.Fatalf("Failed to create split dialer: %v", err)
}
// 3. Configure an HTTP client to use our custom split dialer for TCP connections.
httpClient := &http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return dialer.DialStream(ctx, addr)
},
},
}
// 4. Use the custom client to make the HTTP GET request.
resp, err := httpClient.Get(url)
if err != nil {
log.Fatalf("HTTP request failed: %v", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Failed to read response body: %v", err)
}
fmt.Println(string(body))
}
保存代码后,在终端中运行以下命令,确保 go.mod
文件已正确更新。
go mod tidy
第 4 步:运行应用
代码就绪后,您现在可以运行 splitfetch
应用了。
在 splitfetch
目录中,在终端中运行以下命令,并将网址作为参数传递:
go run . https://getoutline.org
这会编译并运行应用,从而显示网页的 HTML 内容。
如果您想创建和分发一个无需 go
即可运行的独立程序,请使用 go build
命令:
Linux 和 Mac
go build -o splitfetch .
Windows
go build -o splitfetch.exe .
构建完成后,您就可以分发和运行应用了。 例如:
./splitfetch https://getoutline.org