mstrans

package module
v0.0.0-...-eef3193 Latest Latest
Warning

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

Go to latest
Published: Jan 26, 2026 License: MIT Imports: 10 Imported by: 0

README

not production code

  • don't expect it will work so well

mod download

GOPRIVATE=gitee.com/EEPPEE_admin/mstrans
go get gitee.com/EEPPEE_admin/mstrans

sample usage

auto get token

package main

import (
	"fmt"
	"time"

	"gitee.com/EEPPEE_admin/mstrans"
)

func main() {
	// 1. Create a client (custom timeout: 15 seconds)
	client := mstrans.NewClient(15 * time.Second)

	// 2. Simple English → Chinese translation (simplified API)
	enText := "Frontend development with Go and Vue is fun and challenging"
	zhResult, err := client.TranslateSimple(enText, "en", "zh-Hans")
	if err != nil {
		fmt.Printf("❌ Simple translation failed: %v\n", err)
	} else {
		fmt.Println("✅ English → Chinese (Simple):")
		fmt.Printf("Original: %s\nTranslated: %s\n\n", enText, zhResult)
	}

	// 3. Chinese → English translation (full API for more details)
	zhText := "Go语言的Microsoft Translator库非常易用"
	fullResults, err := client.Translate(zhText, "zh-Hans", "en")
	if err != nil {
		fmt.Printf("❌ Full translation failed: %v\n", err)
	} else {
		fmt.Println("✅ Chinese → English (Full API):")
		fmt.Printf("Original: %s\n", zhText)
		fmt.Printf("Translated: %s\n", fullResults[0].Translations[0].Text)
		fmt.Printf("Detected Source Language: %s (confidence: %.2f)\n",
			fullResults[0].DetectedLanguage.Language,
			fullResults[0].DetectedLanguage.Score)
	}

	// 4. Translate multiple texts at once
	multiTexts := []string{"Hello World", "Microsoft Translator API"}
	multiResults, err := client.Translate(multiTexts, "auto-detect", "zh-Hans")
	if err != nil {
		fmt.Printf("\n❌ Multi-text translation failed: %v\n", err)
	} else {
		fmt.Println("\n✅ Multi-text Translation:")
		for i, res := range multiResults {
			fmt.Printf("%d. %s → %s\n", i+1, multiTexts[i], res.Translations[0].Text)
		}
	}
}

set token manually when failed

  • you may see below failed text, just click the url, and copy its content
❌ Simple translation failed: get token: fetch token: Get "https://edge.microsoft.com/translate/auth": context deadline exceeded (Client.Timeout exceeded while awaiting headers)
package main

import (
	"fmt"
	"time"

	"gitee.com/EEPPEE_admin/mstrans"
)

func main() {
	// 1. 创建 Client,延长超时时间到 30 秒(可选)
	client := mstrans.NewClient(30 * time.Second)

	// 2. 设置你手动获取的 Token(关键!)
	manualToken := "eyJhbGciOiJFUzI1NiIsImtpZCI6ImtleTEiLCJ0eXAiOiJKV1QifQ.eyJyZWdpb24iOiJnbG9iYWwiLCJzdWJzY3JpcHRpb24taWQiOiI2ZjY1YjliY2JkNjA0ZDg4ODhiZWI2M2I4MTM4ODZlZSIsInByb2R1Y3QtaWQiOiJUZXh0VHJhbnNsYXRvci5TMyIsImNvZ25pdGl2ZS1zZXJ2aWNlcy1lbmRwb2ludCI6Imh0dHBzOi8vYXBpLmNvZ25pdGl2ZS5taWNyb3NvZnQuY29tL2ludGVybmFsL3YxLjAvIiwiYXp1cmUtcmVzb3VyY2UtaWQiOiIvc3Vic2NyaXB0aW9ucy84MWZjMTU3Yi0zMDdlLTRjMjEtOWY3MS0zM2QxMDMwNGRmMzMvcmVzb3VyY2VHcm91cHMvRWRnZV9UcmFuc2xhdGVfUkcvcHJvdmlkZXJzL01pY3Jvc29mdC5Db2duaXRpdmVTZXJ2aWNlcy9hY2NvdW50cy9UcmFuc2xhdGUiLCJzY29wZSI6Imh0dHBzOi8vYXBpLm1pY3Jvc29mdHRyYW5zbGF0b3IuY29tLyIsImF1ZCI6InVybjptcy5taWNyb3NvZnR0cmFuc2xhdG9yIiwiZXhwIjoxNzY5MjY5MDM1LCJpc3MiOiJ1cm46bXMuY29nbml0aXZlc2VydmljZXMifQ.fyVikEiV2l92iEYkT-wQJy3w11mZZV_6Ce-HuCIiVh_VscfnA-IvpfeSZJ6x37wazBgeRnFBbExQ4deYGPx6ng"
	client.SetManualToken(manualToken)

	// 3. 测试翻译
	enText := "Frontend development with Go and Vue is fun and challenging"
	zhResult, err := client.TranslateSimple(enText, "en", "zh-Hans")
	if err != nil {
		fmt.Printf("❌ Simple translation failed: %v\n", err)
	} else {
		fmt.Println("✅ English → Chinese (Simple):")
		fmt.Printf("Original: %s\nTranslated: %s\n\n", enText, zhResult)
	}
}

original idea from node.js bing-translate-api

Documentation

Index

Constants

View Source
const (
	DefaultUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
)

DefaultUserAgent matches the JS default (ensures compatibility with Microsoft's API)

Variables

View Source
var LangMap map[string]string

LangMap maps language codes to names (e.g., "zh-Hans": "Chinese Simplified")

Functions

func GetLangCode

func GetLangCode(lang string) string

GetLangCode normalizes language input (e.g., "zh" → "zh-Hans", "english" → "en")

func IsLangSupported

func IsLangSupported(lang string) bool

IsLangSupported checks if a language code/name is supported

Types

type Client

type Client struct {
	ManualToken string // 手动设置的 Token(优先级高于自动获取)
	// contains filtered or unexported fields
}

Client is the main struct for Microsoft Translator (thread-safe)

func NewClient

func NewClient(timeout ...time.Duration) *Client

NewClient creates a new Translator client (custom timeout optional)

func (*Client) SetManualToken

func (c *Client) SetManualToken(token string)

SetManualToken 方法,用于手动设置 Token

func (*Client) SetUserAgent

func (c *Client) SetUserAgent(ua string)

SetUserAgent overrides the default User-Agent (for customization)

func (*Client) Translate

func (c *Client) Translate(text any, from, to string) ([]TranslationResult, error)

Translate is the core API: translates text (single/multiple) between languages - text: string or []string (content to translate) - from: source language (use "" or "auto-detect" for auto-detection) - to: target language (e.g., "zh-Hans", "en")

func (*Client) TranslateSimple

func (c *Client) TranslateSimple(text, from, to string) (string, error)

TranslateSimple is a simplified API for single-text translation (returns only translated text)

type TranslationResult

type TranslationResult struct {
	DetectedLanguage struct {
		Language string  `json:"language"`
		Score    float64 `json:"score"`
	} `json:"detectedLanguage,omitempty"`
	Translations []struct {
		Text            string `json:"text"`
		To              string `json:"to"`
		Transliteration struct {
			Text string `json:"text,omitempty"`
		} `json:"transliteration,omitempty"`
	} `json:"translations"`
}

TranslationResult represents a single translation result (matches MS API response)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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