-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
101 lines (84 loc) · 2.23 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Copyright (c) 2014 Akeda Bagus <[email protected]>
// Licensed under MIT license.
//
// Utilitas CLI untuk menterjemahkan teks (menggunakan Yandex API)
package main
import (
"encoding/json"
"flag"
"fmt"
"net/http"
"net/url"
"os"
"runtime"
"strings"
)
const (
TranslateURL = "https://translate.yandex.net/api/v1.5/tr.json/translate"
DefaultAPIKey = "trnsl.1.1.20141203T051248Z.447b0f450a99eeab.923b88210e4887f07e143074a15631f39a313156"
)
type Response struct {
Code int
Lang string
Text []string
}
var (
from = flag.String("from", "en", "Terjemahin dari bahasa XX, default en.")
to = flag.String("to", "id", "Terjemahin ke bahasa YY, default id.")
api_key = flag.String("api_key", DefaultAPIKey, fmt.Sprintf("Yandex API key, default %s", DefaultAPIKey))
responseErrors map[int]string
)
func init() {
responseErrors = map[int]string{
401: "Invalid API key",
402: "API key sudah diblok",
403: "Permintaan sudah mencapai limit harian",
404: "Permintaan sudah mencapai limit harian untuk jumlah teks yang diterjemahkan",
413: "Panjang teks melebihi batas",
422: "Teks tidak dapat diterjemahkan",
501: fmt.Sprintf("Tidak mendukung penterjemahan dari %s ke %s", *from, *to),
}
}
func usage() {
fmt.Fprintf(os.Stderr, "usage: terjemahin [flags] teks\n")
flag.PrintDefaults()
os.Exit(2)
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
flag.Usage = usage
flag.Parse()
if flag.NArg() == 0 {
usage()
}
terjemahin(flag.Args())
}
func terjemahin(text []string) {
v := url.Values{}
v.Set("key", *api_key)
v.Set("lang", fmt.Sprintf("%s-%s", *from, *to))
for _, t := range text {
v.Add("text", t)
}
resp, err := http.PostForm(TranslateURL, v)
if err != nil {
fmt.Fprintf(os.Stderr, "Error when requesting: %s\n", err)
os.Exit(2)
}
defer resp.Body.Close()
if errMsg, foundErr := responseErrors[resp.StatusCode]; foundErr {
fmt.Fprintf(os.Stderr, "Error: %s\n", errMsg)
os.Exit(2)
}
if resp.StatusCode != http.StatusOK {
fmt.Fprintf(os.Stderr, "Error status code: %d\n", resp.StatusCode)
os.Exit(2)
}
r := new(Response)
err = json.NewDecoder(resp.Body).Decode(r)
if err != nil {
fmt.Fprintf(os.Stderr, "Error decoding JSON: %s\n", err)
os.Exit(2)
}
fmt.Println(strings.Join(r.Text, " "))
}