Skip to content

How do I translate a text or string in Golang?

How do I translate a text or string in Golang?

for translating a text or string in Golang, first step is create function support for function translate. Set variable source and target language.

const Auto = "auto"
var (
	LangID = language.Indonesian.String()
	LangEn = language.English.String()
)

Create Function defaultSourceLang returns the default source language. It takes a string parameter s representing the source language. It trims any leading or trailing whitespace from the string. If the trimmed string is empty, it returns the constant value Auto. Otherwise, it returns the trimmed string.

func defaultSourceLang(s string) string {
	// Trim any leading or trailing whitespace from the string
	s = strings.TrimSpace(s)

	// If the trimmed string is empty, return the constant value `Auto`
	if s == "" {
		return Auto
	}

	// Otherwise, return the trimmed string
	return s
}

create function defaultTargetLang returns the default target language. It takes a string parameter s representing the target language. It trims any leading or trailing whitespace from the string. If the trimmed string is empty, it returns the constant value LangID. Otherwise, it returns the trimmed string.

func defaultTargetLang(s string) string {
	// Trim any leading or trailing whitespace from the string
	s = strings.TrimSpace(s)

	// If the trimmed string is empty, return the constant value LangID
	if s == "" {
		return LangID
	}

	// Otherwise, return the trimmed string
	return s
}

create function QueryEscape encodes the given string for use in a URL query parameter by trimming any leading or trailing whitespace and then URL encoding the result.

Parameters:

  • s: The string to be encoded.

Returns:

  • The encoded string.
func QueryEscape(s string) string {
	// Trim any leading or trailing whitespace from the string
	s = strings.TrimSpace(s)

	// URL encode the trimmed string and return the result
	return url.QueryEscape(s)
}

Step end create function Translate to translate a text or string in Golang. Translate translates the given source text from the given source language to the given target language.

It uses the Google Translate API to perform the translation.

Parameters:

  • source: The source text to be translated.
  • sourceLang: The source language of the text to be translated. If this parameter is empty, the default source language is used.
  • targetLang: The target language of the text to be translated. If this parameter is empty, the default target language is used.

Returns:

  • The translated text, or an error if the translation fails.
func Translate(source, sourceLang, targetLang string) (string, error) {
	var (
		translation []interface{}
		text        []string
	)

	// URL encode the source text and construct the API URL
	encodedSource := QueryEscape(source)
	url := fmt.Sprintf("https://translate.googleapis.com/translate_a/single?client=gtx&sl=%s&tl=%s&dt=t&q=%s",
		defaultSourceLang(sourceLang), defaultTargetLang(targetLang), encodedSource)

	// Make the API request
	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// Read the response body
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	// Unmarshal the response JSON
	err = json.Unmarshal(body, &translation)
	if err != nil {
		return "", err
	}

	// Extract the translated text from the response
	if len(translation) > 0 {
		inner := translation[0]
		for _, slice := range inner.([]interface{}) {
			for _, translatedText := range slice.([]interface{}) {
				text = append(text, fmt.Sprintf("%v", translatedText))
				break
			}
		}
		return strings.Join(text, ""), nil
	}

	// Return an error if no translated text is found in the response
	return "", errors.New("no translated data in response")
}

Lets try out Translate function in Golang

package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"

	"golang.org/x/text/language"
)

const Auto = "auto"
var (
	LangID = language.Indonesian.String()
	LangEn = language.English.String()
)

func defaultSourceLang(s string) string {
	s = strings.TrimSpace(s)
	if s == "" {
		return Auto
	}
	return s
}

func defaultTargetLang(s string) string {
	s = strings.TrimSpace(s)
	if s == "" {
		return LangID
	}
	return s
}

func QueryEscape(s string) string {
	return url.QueryEscape(strings.TrimSpace(s))
}

func Translate(source, sourceLang, targetLang string) (string, error) {
	var (
		translation []interface{}
		text        []string
	)

	encodedSource := QueryEscape(source)
	url := fmt.Sprintf("https://translate.googleapis.com/translate_a/single?client=gtx&sl=%s&tl=%s&dt=t&q=%s",
		defaultSourceLang(sourceLang), defaultTargetLang(targetLang), encodedSource)

	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	err = json.Unmarshal(body, &translation)
	if err != nil {
		return "", err
	}

	if len(translation) > 0 {
		inner := translation[0]
		for _, slice := range inner.([]interface{}) {
			for _, translatedText := range slice.([]interface{}) {
				text = append(text, fmt.Sprintf("%v", translatedText))
				break
			}
		}
		return strings.Join(text, ""), nil
	}

	return "", errors.New("no translated data in response")
}

func main() {
	originalText := "Hello World, I am Adam Nasrudin"
	message, err := Translate(originalText, LangEn, LangID)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	fmt.Printf("Original: %s\n", originalText) // Original: Hello World, I am Adam Nasrudin
	fmt.Printf("Translated: %s\n", message)    // Translated: Halo Dunia, Saya Adam Nasrudin
	fmt.Println("")

	originalText = "Hallo dunia, perkenalkan nama saya Adam Nasrudin"
	message, err = Translate(originalText, Auto, LangEn)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	fmt.Printf("Original: %s\n", originalText) // Original: Hallo dunia, perkenalkan nama saya Adam Nasrudin
	fmt.Printf("Translated: %s\n", message)    // Translated: Hello world, my name is Adam Nasrudin
}

have fun your code, thanks for reading my blog