-
Notifications
You must be signed in to change notification settings - Fork 0
/
phteven.go
46 lines (37 loc) · 1.02 KB
/
phteven.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
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
http.HandleFunc("/", homeHandler)
http.HandleFunc("/phteven", phtevenHandler)
http.ListenAndServe(":8080", nil)
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "This is the home page!")
}
func phtevenHandler(w http.ResponseWriter, r *http.Request) {
text := r.URL.Query().Get("text")
body, _ := getPhtevenResponseBody(text)
fmt.Fprintf(w, "%s", body)
}
func getPhtevenResponseBody(text string) ([]byte, error) {
url := "http://api.phteven.io/translate/"
dog := Dog{"Phteven", 3, text}
requestBody := bytes.NewBufferString(fmt.Sprintf("text=%s", dog.say()))
response, err := http.Post(url, "application/x-www-form-urlencoded", requestBody)
if err != nil {
fmt.Printf("Error sending request: %v\n", err)
return []byte(""), err
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Printf("Error reading body: %v\n", err)
return []byte(""), err
}
return body, nil
}