gtranslate/api.go

37 lines
680 B
Go

package main
import (
"fmt"
"net/http"
)
func writeError(w http.ResponseWriter, status int, err interface{}) {
w.WriteHeader(status)
w.Write([]byte(fmt.Sprintln(err)))
}
func ApiHandler(w http.ResponseWriter, req *http.Request) {
from := req.FormValue("from")
if from == "" {
writeError(w, 400, "'from' field is missing")
return
}
to := req.FormValue("to")
if to == "" {
writeError(w, 400, "'to' field is missing")
return
}
text := req.FormValue("text")
if text == "" {
writeError(w, 400, "'text' field is missing")
return
}
translation, err := Translate(from, to, text)
if err != nil {
writeError(w, 500, err)
}
w.Write([]byte(translation))
}