fern-api / fern

Input OpenAPI. Output SDKs and Docs.
https://buildwithfern.com
Apache License 2.0
2.69k stars 151 forks source link

feat(go): Simplify generated code #5213

Closed amckinney closed 1 day ago

amckinney commented 2 days ago

This adapts generated endpoint structure to clean up the generated code and reduce repetition. This also proposes a simpler errorDecoder constructor, splits specific method invocations across multiple lines, and removes a variety of unnecessary newlines across the SDK.

Now, users are presented with an endpoint that looks something along the lines of the following:

func (c *Client) Get(
    ctx context.Context,
    id string,
    opts ...option.RequestOption,
) (string, error) {
    options := core.NewRequestOptions(opts...)
    baseURL := internal.ResolveBaseURL(
        options.BaseURL,
        c.baseURL,
        "https://api.foo.io/v1",
    )
    endpointURL := internal.EncodeURL(
        baseURL+"/%v",
        id,
    )
    headers := internal.MergeHeaders(
        c.header.Clone(),
        options.ToHeader(),
    )
    errorCodes := map[int]func() error{
        400: func(apiError *core.APIError) error {
            return &acme.UntypedError{
                            APIError: apiError,
                         }
        },
        404: func(apiError *core.APIError) error {
            return &acme.NotFoundError{
                            APIError: apiError,
                         }
        },
    }

    var response string
    if err := c.caller.Call(
        ctx,
        &internal.CallParams{
            URL:             endpointURL,
            Method:          http.MethodGet,
            MaxAttempts:     options.MaxAttempts,
            Headers:         headers,
            BodyProperties:  options.BodyProperties,
            QueryParameters: options.QueryParameters,
            Client:          options.HTTPClient,
            Response:        &response,
            ErrorDecoder:    internal.NewErrorDecoder(errorCodes),
        },
    ); err != nil {
        return "", err
    }
    return response, nil
}
github-actions[bot] commented 2 days ago

🌿 Preview your docs: https://fern-preview-e34f78e1-a17f-4c18-9918-aead719ace56.docs.buildwithfern.com/learn