-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.go
80 lines (66 loc) · 1.81 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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/bregydoc/gtranslate"
"github.com/rs/cors"
)
type TranslateRequest struct {
Text string `json:"text"`
To string `json:"to"`
}
type TranslateResponse struct {
TranslatedText string `json:"translatedText,omitempty"`
Status bool `json:"status"`
Message string `json:"message"`
}
func TranslateHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var request TranslateRequest
err := json.NewDecoder(r.Body).Decode(&request)
if err != nil {
sendErrorResponse(w, "Invalid request payload", http.StatusBadRequest)
return
}
translated, err := gtranslate.TranslateWithParams(request.Text, gtranslate.TranslationParams{
From: "auto",
To: request.To,
})
if err != nil {
sendErrorResponse(w, "Translation failed", http.StatusInternalServerError)
return
}
response := TranslateResponse{
TranslatedText: translated,
Status: true,
Message: "",
}
sendJSONResponse(w, response, http.StatusOK)
}
func sendErrorResponse(w http.ResponseWriter, message string, statusCode int) {
response := TranslateResponse{
Status: false,
Message: message,
}
sendJSONResponse(w, response, statusCode)
}
func sendJSONResponse(w http.ResponseWriter, data interface{}, statusCode int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
err := json.NewEncoder(w).Encode(data)
if err != nil {
log.Printf("Failed to encode JSON response: %v", err)
}
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/translate", TranslateHandler)
c := cors.Default().Handler(mux)
fmt.Println("Starting server on http://localhost:8000")
log.Fatal(http.ListenAndServe(":8000", c))
}