-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
73 lines (60 loc) · 1.49 KB
/
Copy pathmain.go
File metadata and controls
73 lines (60 loc) · 1.49 KB
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
package main
import (
"encoding/json"
"fmt"
"github.com/gokhanamal/tureng-api/controller"
"log"
"net/http"
"strings"
)
type Error struct {
Message string `json:"message, omitempty"`
}
type Response struct {
Count int `json:"count"`
Phrases []controller.Phrase `json:"phrases"`
}
func writeJSON(w http.ResponseWriter, v interface{}) {
jsonData, err := json.Marshal(v)
if err != nil {
log.Printf("json write error %v", err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
err := Error{
"Please use /translate",
}
fmt.Print(err)
w.WriteHeader(http.StatusNotFound)
writeJSON(w, err)
})
http.HandleFunc("/translate", func(w http.ResponseWriter, req *http.Request) {
queries := req.URL.Query()
phrase := queries["phrase"]
if phrase == nil {
err := Error{
"Missing query, you should add to your request phrase that want to translate.",
}
w.WriteHeader(http.StatusUnprocessableEntity)
writeJSON(w, err)
return
}
response, err := controller.FetchFromTureng(strings.Join(phrase, ""))
if err != nil {
err := Error{
"Someting went wrong while fetching the phrases from Tureng.",
}
w.WriteHeader(http.StatusUnprocessableEntity)
writeJSON(w, err)
}
w.WriteHeader(http.StatusOK)
writeJSON(w, Response{Count: len(response), Phrases: response})
})
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Printf("%s", err)
}
}