-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDictionaryExamples.go
80 lines (73 loc) · 2.41 KB
/
DictionaryExamples.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
)
func main() {
/*
* Read your subscription key from an env variable.
* Please note: You can replace this code block with
* var subscriptionKey = "YOUR_SUBSCRIPTION_KEY" if you don't
* want to use env variables. If so, be sure to delete the "os" import.
*/
if "" == os.Getenv("TRANSLATOR_TEXT_SUBSCRIPTION_KEY") {
log.Fatal("Please set/export the environment variable TRANSLATOR_TEXT_SUBSCRIPTION_KEY.")
}
subscriptionKey := os.Getenv("TRANSLATOR_TEXT_SUBSCRIPTION_KEY")
if "" == os.Getenv("TRANSLATOR_TEXT_ENDPOINT") {
log.Fatal("Please set/export the environment variable TRANSLATOR_TEXT_ENDPOINT.")
}
endpoint := os.Getenv("TRANSLATOR_TEXT_ENDPOINT")
uri := endpoint + "/dictionary/examples?api-version=3.0"
/*
* This calls our breakSentence function, which we'll
* create in the next section. It takes a single argument,
* the subscription key.
*/
dictionaryExamples(subscriptionKey, uri)
}
func dictionaryExamples(subscriptionKey string, uri string) {
// Build the request URL. See: https://golang.org/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
q.Add("from", "en")
q.Add("to", "es")
u.RawQuery = q.Encode()
// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
Text string
Translation string
}{
{
Text: "How are you? I am fine. What did you do today?",
Translation: "¿Cómo estás? Estoy bien. ¿Qué hiciste hoy?",
},
}
b, _ := json.Marshal(body)
// Build the HTTP POST request
req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b))
if err != nil {
log.Fatal(err)
}
// Add required headers to the request
req.Header.Add("Ocp-Apim-Subscription-Key", subscriptionKey)
req.Header.Add("Content-Type", "application/json")
// Call the Translator Text API
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// Decode the JSON response
var result interface{}
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
log.Fatal(err)
}
// Format and print the response to terminal
prettyJSON, _ := json.MarshalIndent(result, "", " ")
fmt.Printf("%s\n", prettyJSON)
}