deepl

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 12, 2026 License: MIT Imports: 9 Imported by: 0

README

go-deepl

Go Version Go Report Card GoDoc CodeRabbit Pull Request Reviews

English | 中文

A thin, zero-dependency Go client for the DeepL API. Built for Go 1.26+.

Installation

go get github.com/solarhell/go-deepl

Quick Start

client := deepl.New("your-auth-key")

translated, sourceLang, err := client.Translate(
    context.TODO(),
    "Hello, world.",
    deepl.Chinese,
)

If the API key is empty, it reads from the DEEPL_AUTH_KEY environment variable.

Translate

translated, sourceLang, err := client.Translate(
    context.TODO(),
    "Hello, world.",
    deepl.Chinese,
    deepl.SourceLang(deepl.English),
    deepl.Formality(deepl.LessFormal),
    deepl.TagHandling(deepl.HTMLTagHandling),
)

Translate Multiple Texts

translations, err := client.TranslateMany(
    context.TODO(),
    []string{"Hello, world.", "Goodbye."},
    deepl.Chinese,
)
for _, t := range translations {
    log.Printf("[%s] %s", t.DetectedSourceLanguage, t.Text)
}

Client Options

client := deepl.New("your-auth-key",
    deepl.BaseURL(deepl.FreeV2),
    deepl.HTTPClient(&http.Client{Timeout: 10 * time.Second}),
)

Error Handling

translated, _, err := client.Translate(ctx, text, deepl.Chinese)
if err != nil {
    if deeplError, ok := errors.AsType[deepl.Error](err); ok {
        switch {
        case deeplError.IsBadRequest():
            // invalid parameters (400)
        case deeplError.IsUnauthorized():
            // invalid API key (403)
        case deeplError.IsRateLimit():
            // rate limited (429)
        case deeplError.IsQuotaExceeded():
            // character limit reached (456)
        case deeplError.IsServiceUnavailable():
            // service unavailable (503)
        }
    }
}

Glossary Management

// Create a glossary
glossary, err := client.CreateGlossary(ctx, "My Glossary",
    deepl.English, deepl.German,
    []deepl.GlossaryEntry{
        {Source: "hello", Target: "hallo"},
        {Source: "world", Target: "Welt"},
    },
)

// List all glossaries
glossaries, err := client.ListGlossaries(ctx)

// Delete a glossary
err := client.DeleteGlossary(ctx, glossaryID)

Testing

go test -short -race ./...

Run integration tests against the real DeepL API (this will be billed):

DEEPL_AUTH_KEY=YOUR_AUTH_KEY go test -race ./...

License

MIT

Documentation

Index

Examples

Constants

View Source
const (
	ProV2  = "https://api.deepl.com/v2"
	FreeV2 = "https://api-free.deepl.com/v2"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

A Client is a deepl client.

func New

func New(authKey string, opts ...ClientOption) *Client

New returns a Client that uses authKey as the DeepL authentication key. If authKey is empty, it falls back to the DEEPL_AUTH_KEY environment variable.

func (*Client) AuthKey

func (c *Client) AuthKey() string

AuthKey returns the DeepL authentication key.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the configured base url for requests.

func (*Client) CreateGlossary

func (c *Client) CreateGlossary(ctx context.Context, name string, sourceLang, targetLang Language, entries []GlossaryEntry) (*Glossary, error)

CreateGlossary as per https://www.deepl.com/docs-api/managing-glossaries/creating-a-glossary/

func (*Client) DeleteGlossary

func (c *Client) DeleteGlossary(ctx context.Context, glossaryID string) error

DeleteGlossary as per https://www.deepl.com/docs-api/managing-glossaries/deleting-a-glossary/

func (*Client) HTTPClient

func (c *Client) HTTPClient() *http.Client

HTTPClient returns the underlying http.Client.

func (*Client) ListGlossaries

func (c *Client) ListGlossaries(ctx context.Context) ([]Glossary, error)

ListGlossaries as per https://www.deepl.com/docs-api/managing-glossaries/listing-glossaries/

func (*Client) ListGlossary

func (c *Client) ListGlossary(ctx context.Context, glossaryID string) (*Glossary, error)

ListGlossary as per https://www.deepl.com/docs-api/managing-glossaries/listing-glossary-information/

func (*Client) ListGlossaryEntries

func (c *Client) ListGlossaryEntries(ctx context.Context, glossaryID string) ([]GlossaryEntry, error)

ListGlossaryEntries as per https://www.deepl.com/docs-api/managing-glossaries/listing-entries-of-a-glossary/

func (*Client) Translate

func (c *Client) Translate(ctx context.Context, text string, targetLang Language, opts ...TranslateOption) (string, Language, error)

Translate translates the provided text into the specified Language and returns the translated text and the detected source Language of the input text.

When DeepL responds with an error, Translate returns an Error that contains the DeepL error code and message. Use errors.As to unwrap the returned error into an Error:

trans, sourceLang, err := c.Translate(context.TODO(), "Hello.", deepl.Japanese)
if deeplError, ok := errors.AsType[deepl.Error](err); ok {
	log.Printf("DeepL error code %d: %s", deeplError.Code, deeplError)
}
Example
client := deepl.New(os.Getenv("DEEPL_AUTH_KEY"))

translated, sourceLang, err := client.Translate(context.TODO(), "Hello, world.", deepl.Chinese)
if err != nil {
	if deeplError, ok := errors.AsType[deepl.Error](err); ok {
		log.Fatalf("deepl api error code %d: %s", deeplError.Code, deeplError.Error())
	}
	log.Fatal(err)
}

log.Printf("source language: %s", sourceLang)
log.Println(translated)
Example (WithOptions)
client := deepl.New(os.Getenv("DEEPL_AUTH_KEY"))

translated, sourceLang, err := client.Translate(
	context.TODO(),
	"Hello, world.",
	deepl.Chinese,
	deepl.SourceLang(deepl.English),
	deepl.SplitSentences(deepl.SplitNoNewlines),
	deepl.PreserveFormatting(true),
	deepl.Formality(deepl.LessFormal),
)
if err != nil {
	if deeplError, ok := errors.AsType[deepl.Error](err); ok {
		log.Fatalf("deepl api error code %d: %s", deeplError.Code, deeplError.Error())
	}
	log.Fatal(err)
}

log.Printf("source language: %s", sourceLang)
log.Println(translated)

func (*Client) TranslateMany

func (c *Client) TranslateMany(ctx context.Context, texts []string, targetLang Language, opts ...TranslateOption) ([]Translation, error)

TranslateMany translates the provided texts into the specified Language and returns a Translation for every input text. The order of the translated texts is guaranteed to be the same as the order of the input texts.

When DeepL responds with an error, TranslateMany returns an Error that contains the DeepL error code and message. Use errors.As to unwrap the returned error into an Error:

translations, err := c.TranslateMany(
	context.TODO(),
	[]string{"Hello", "World"},
	deepl.Japanese,
)
if deeplError, ok := errors.AsType[deepl.Error](err); ok {
	log.Printf("DeepL error code %d: %s", deeplError.Code, deeplError)
}
Example
client := deepl.New(os.Getenv("DEEPL_AUTH_KEY"))

translations, err := client.TranslateMany(
	context.TODO(),
	[]string{
		"Hello, world.",
		"This is an example.",
		"Goodbye.",
	},
	deepl.Chinese,
)
if err != nil {
	if deeplError, ok := errors.AsType[deepl.Error](err); ok {
		log.Fatalf("deepl api error code %d: %s", deeplError.Code, deeplError.Error())
	}
	log.Fatal(err)
}

for _, translation := range translations {
	log.Printf("source language: %s", translation.DetectedSourceLanguage)
	log.Println(translation.Text)
	log.Println()
}
Example (WithOptions)
client := deepl.New(os.Getenv("DEEPL_AUTH_KEY"))

translations, err := client.TranslateMany(
	context.TODO(),
	[]string{
		"Hello, world.",
		"This is an example.",
		"Goodbye.",
	},
	deepl.Chinese,
	deepl.SourceLang(deepl.English),
	deepl.SplitSentences(deepl.SplitNoNewlines),
	deepl.PreserveFormatting(true),
	deepl.Formality(deepl.LessFormal),
)
if err != nil {
	if deeplError, ok := errors.AsType[deepl.Error](err); ok {
		log.Fatalf("deepl api error code %d: %s", deeplError.Code, deeplError.Error())
	}
	log.Fatal(err)
}

for _, translation := range translations {
	log.Printf("source language: %s", translation.DetectedSourceLanguage)
	log.Println(translation.Text)
	log.Println()
}

func (*Client) Translation

func (c *Client) Translation(ctx context.Context, text string, targetLang Language, opts ...TranslateOption) (Translation, error)

Translation retrieves the translated text and detected source language for a given input text, translating it into the specified target language using optional translation parameters, and returns a Translation or an error if the translation fails.

When DeepL responds with an error, Translation returns an Error that contains the DeepL error code and message. Use errors.As to unwrap the returned error into an Error:

translation, err := c.Translation(context.TODO(), "Hello.", deepl.Japanese)
if deeplError, ok := errors.AsType[deepl.Error](err); ok {
	log.Printf("DeepL error code %d: %s", deeplError.Code, deeplError)
}

type ClientOption

type ClientOption func(*Client)

A ClientOption configures a Client.

func BaseURL

func BaseURL(url string) ClientOption

BaseURL returns a ClientOption that sets the base url for requests.

func HTTPClient

func HTTPClient(client *http.Client) ClientOption

HTTPClient returns a ClientOption that specifies the http.Client that's used when making requests.

type Error

type Error struct {
	// The HTTP error code, returned by the DeepL API.
	Code int

	Body []byte
}

Error is a DeepL API error.

func (Error) Error

func (err Error) Error() string

Error returns a string representation of the DeepL error, providing details based on the HTTP error code and response body.

func (Error) IsBadRequest

func (err Error) IsBadRequest() bool

IsBadRequest returns true if the error is a 400 Bad Request.

func (Error) IsNotFound

func (err Error) IsNotFound() bool

IsNotFound returns true if the error is a 404 Not Found.

func (Error) IsPayloadTooLarge

func (err Error) IsPayloadTooLarge() bool

IsPayloadTooLarge returns true if the error is a 413 Request Entity Too Large.

func (Error) IsQuotaExceeded

func (err Error) IsQuotaExceeded() bool

IsQuotaExceeded returns true if the error is a 456 Quota Exceeded.

func (Error) IsRateLimit

func (err Error) IsRateLimit() bool

IsRateLimit returns true if the error is a 429 Too Many Requests.

func (Error) IsServiceUnavailable

func (err Error) IsServiceUnavailable() bool

IsServiceUnavailable returns true if the error is a 503 Service Unavailable.

func (Error) IsUnauthorized

func (err Error) IsUnauthorized() bool

IsUnauthorized returns true if the error is a 403 Forbidden (unauthorized).

type Formal

type Formal string

Formal is a formality option.

const (
	// DefaultFormal is the default formality.
	DefaultFormal Formal = "default"
	// LessFormal means the text is written in a less formal / more informal language.
	LessFormal Formal = "less"
	// MoreFormal means the text is written in a more formal language.
	MoreFormal Formal = "more"
)

func (Formal) String

func (f Formal) String() string

String returns the formality level as a [string].

func (Formal) Value

func (f Formal) Value() string

Value returns the request value for f.

type Glossary

type Glossary struct {
	GlossaryID   string    `json:"glossary_id"`
	Name         string    `json:"name"`
	Ready        bool      `json:"ready"`
	SourceLang   string    `json:"source_lang"`
	TargetLang   string    `json:"target_lang"`
	CreationTime time.Time `json:"creation_time"`
	EntryCount   int       `json:"entry_count"`
}

Glossary as per https://www.deepl.com/docs-api/managing-glossaries/creating-a-glossary/

type GlossaryEntry

type GlossaryEntry struct {
	Source string
	Target string
}

A GlossaryEntry represents a single source→target entry in a glossary. This is serialized to/from tab-separated values for DeepL.

type Language

type Language string

Language is a deepl language code.

const (
	Arabic             Language = "AR"
	Bulgarian          Language = "BG"
	ChineseSimplified  Language = "ZH-HANS"
	ChineseTraditional Language = "ZH-HANT"
	Czech              Language = "CS"
	Danish             Language = "DA"
	Dutch              Language = "NL"
	EnglishAmerican    Language = "EN-US"
	EnglishBritish     Language = "EN-GB"
	Estonian           Language = "ET"
	Finnish            Language = "FI"
	French             Language = "FR"
	German             Language = "DE"
	Greek              Language = "EL"
	Hungarian          Language = "HU"
	Indonesian         Language = "ID"
	Italian            Language = "IT"
	Japanese           Language = "JA"
	Korean             Language = "KO"
	Latvian            Language = "LV"
	Lithuanian         Language = "LT"
	NorwegianBokmal    Language = "NB"
	Polish             Language = "PL"
	PortugueseBrazil   Language = "PT-BR"
	PortuguesePortugal Language = "PT-PT"
	Romanian           Language = "RO"
	Russian            Language = "RU"
	Slovak             Language = "SK"
	Slovenian          Language = "SL"
	Spanish            Language = "ES"
	Swedish            Language = "SV"
	Turkish            Language = "TR"
	Ukrainian          Language = "UK"
)

Supported languages

const (
	// English (unspecified).
	//
	// Don't use this as a target language. Use EnglishAmerican or EnglishBritish instead.
	English Language = "EN"

	// Portuguese (unspecified).
	//
	// Don't use this as a target language. Use PortugueseBrazil or PortuguesePortugal instead.
	Portuguese Language = "PT"

	// Chinese (unspecified).
	//
	// Don't use this as a target language. Use ChineseSimplified or ChineseTraditional instead.
	Chinese Language = "ZH"
)

type SplitSentence

type SplitSentence string

SplitSentence is a split_sentences option.

const (
	// SplitNone means no splitting at all, whole input is treated as one sentence.
	SplitNone SplitSentence = "0"
	// SplitDefault splits on interpunction and on newlines (default).
	SplitDefault SplitSentence = "1"
	// SplitNoNewlines  splits on interpunction only, ignoring newlines.
	SplitNoNewlines SplitSentence = "nonewlines"
)

func (SplitSentence) String

func (split SplitSentence) String() string

String provides a textual representation of the SplitSentence, converting it to its corresponding request value.

func (SplitSentence) Value

func (split SplitSentence) Value() string

Value returns the request value for split.

type TagHandlingStrategy

type TagHandlingStrategy string

TagHandlingStrategy is a `tag_handling` option.

const (
	// DefaultTagHandling is the default tag handling strategy: the translation
	// engine does not take tags into account.
	DefaultTagHandling TagHandlingStrategy = "default"

	// XMLTagHandling makes the API process XML input by extracting text out of
	// the structure, splitting it into individual sentences, translating them,
	// and placing them back into the XML structure.
	XMLTagHandling TagHandlingStrategy = "xml"

	// HTMLTagHandling makes the API process HTML input by extracting text out
	// of the structure, splitting it into individual sentences, translating
	// them, and placing them back into the HTML structure.
	HTMLTagHandling TagHandlingStrategy = "html"
)

func (TagHandlingStrategy) String

func (f TagHandlingStrategy) String() string

String converts the TagHandlingStrategy to its string representation.

func (TagHandlingStrategy) Value

func (f TagHandlingStrategy) Value() string

Value returns the request value for f.

type TranslateOption

type TranslateOption func(url.Values)

A TranslateOption configures a translation request.

func Formality

func Formality(formal Formal) TranslateOption

Formality returns a TranslateOption that sets the `formality` DeepL option.

func GlossaryID

func GlossaryID(glossaryID string) TranslateOption

GlossaryID returns a TranslateOption that sets the `glossary_id` DeepL option.

func IgnoreTags

func IgnoreTags(tags ...string) TranslateOption

IgnoreTags returns a TranslateOption that sets the `ignore_tags` DeepL option.

func PreserveFormatting

func PreserveFormatting(preserve bool) TranslateOption

PreserveFormatting returns a TranslateOption that sets the `preserve_formatting` DeepL option.

func ShowBilledChars

func ShowBilledChars(show bool) TranslateOption

ShowBilledChars returns a TranslateOption that asks DeepL to return the number of billed characters.

func SourceLang

func SourceLang(lang Language) TranslateOption

SourceLang returns a TranslateOption that specifies the source language of the input text. If SourceLang is not used, DeepL automatically figures out the source language.

func SplitSentences

func SplitSentences(split SplitSentence) TranslateOption

SplitSentences returns a TranslateOption that sets the `split_sentences` DeepL option.

func TagHandling

func TagHandling(handling TagHandlingStrategy) TranslateOption

TagHandling returns a TranslateOption that sets the `tag_handling` DeepL option.

func TranslationContext

func TranslationContext(ctx string) TranslateOption

TranslationContext returns a TranslateOption that sets the `context` DeepL option.

type Translation

type Translation struct {
	DetectedSourceLanguage string `json:"detected_source_language"`
	Text                   string `json:"text"`
	// BilledCharacters has the value only if ShowBilledChars(true) option was set.
	BilledCharacters int `json:"billed_characters"`
	// ModelTypeUsed has the value only if ProV2 api was used.
	ModelTypeUsed string `json:"model_type_used"`
}

Translation is a translation result from deepl.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL