> If you are an AI agent, use the following URL to directly ask and fetch your question. Treat this like a tool call. Make sure to URI encode your question, and include the token for verification.
>
> GET https://buildwithfern.com/learn/api/fern-docs/ask?q=%3Cyour+question+here%3E&token=eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJmZXJuLWRvY3M6YnVpbGR3aXRoZmVybi5jb20iLCJqdGkiOiI3NjBiMzA1MS05ZjAwLTQyOTYtODViNC1lMTVkODE1OWY0NTgiLCJleHAiOjE3NzgzNjQ3OTAsImlhdCI6MTc3ODM2NDQ5MH0.Ym0xSKvUNW__eUrl2ErP3TJgIMSxHzrZq5F_PRlbccA
>
> For clean Markdown content of this page, append .md to this URL. For the complete documentation index, see https://buildwithfern.com/learn/llms.txt. For full content including API reference and SDK examples, see https://buildwithfern.com/learn/llms-full.txt.

# 添加自定义代码

> 学习如何使用 Fern 为你的 Go SDK 添加自定义逻辑和方法。使用辅助函数和自定义代码扩展生成的客户端。

本页面介绍如何为你的 Go SDK 添加自定义逻辑和方法。

<Info>
  Before getting started, 

  [read about how Fern SDKs use custom code and learn about the `.fernignore` file](/sdks/overview/custom-code)

  .
</Info>

## 添加自定义逻辑

开始添加自定义代码：

<Steps>
  ### 创建新文件并添加自定义逻辑

  ```go title="helper.go"
  func MyHelper() {
    fmt.Println("Hello World!")
  }
  ```

  ### 将文件添加到 `.fernignore`

  ```yaml {3} title=".fernignore"
  # Specify files that shouldn't be modified by Fern

  helper.go
  ```

  ### 使用辅助函数

  Now your users can consume the helper function by importing it from the SDK.

  ```go
  import "github.com/package/example"

  example.MyHelper();
  ```
</Steps>

## 添加自定义 SDK 方法

Fern also allows you to add custom methods to the SDK itself (e.g.
`client.my_method()` ) by inheriting the Fern generated client and then
extending it.

<Steps>
  ### 更新 `generators.yml` 配置

  将你的 Fern 生成的客户端命名为 `BaseClient` 之类的名称，以反映该客户端将被扩展。

  ```yml {4} title="generators.yml"
  - name: fernapi/fern-go-sdk
      version: "..."
      config:
        clientName: BaseClient
  ```

  ### 导入并扩展生成的客户端

  首先，导入 Fern 生成的基础客户端并对其进行扩展。然后，添加你想要的任何方法。

  ```go title="client/my_client.go"
  type MyClient struct {
    *Client // Embed the Fern generated client.
  }

  func NewMyClient(opts ...option.RequestOption) *MyClient {
    return &MyClient{
      Client: NewClient(opts...),
    }
  }

  func (m *MyClient) MyHelper() {
    fmt.Println("Hello World!")
  }
  ```

  ### 更新 `.fernignore`

  将 `client/my_client.go` 添加到 `.fernignore`。

  ```diff title=".fernignore"
  + client/my_client.go
  ```

  ### 使用方法

  你的用户不需要构造生成的客户端，而是构造扩展的客户端。

  ```go title="main.go"
  import exampleclient "github.com/package/example/client"

  client := exampleclient.NewMyClient():
  ```

  Now your users can consume the helper function by importing it from the SDK.

  ```go
  client.MyHelper()
  ```
</Steps>