From 1a32c713bc146153bc00d213d62b767828227143 Mon Sep 17 00:00:00 2001 From: Alexey Yerin Date: Mon, 18 Jan 2021 22:52:33 +0300 Subject: [PATCH] Merge api.go into main.go It would be really painful to provide variables there --- api.go | 36 ------------------------------------ main.go | 32 +++++++++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 37 deletions(-) delete mode 100644 api.go diff --git a/api.go b/api.go deleted file mode 100644 index 0d0901a..0000000 --- a/api.go +++ /dev/null @@ -1,36 +0,0 @@ -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)) -} diff --git a/main.go b/main.go index ba80644..fb1f271 100644 --- a/main.go +++ b/main.go @@ -17,6 +17,7 @@ package main import ( + "fmt" "html/template" "log" "net/http" @@ -60,7 +61,31 @@ func main() { tmpl.ExecuteTemplate(w, "index", indexPageData{from, to, text, translation}) }).Methods("GET", "POST") - r.HandleFunc("/api", ApiHandler).Methods("POST") + + r.HandleFunc("/api", func(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)) + }).Methods("POST") // Static files fs := http.FileServer(http.Dir(*staticDir)) @@ -69,3 +94,8 @@ func main() { log.Println("Starting on", *bind) log.Fatalln(http.ListenAndServe(*bind, r)) } + +func writeError(w http.ResponseWriter, status int, err interface{}) { + w.WriteHeader(status) + w.Write([]byte(fmt.Sprintln(err))) +}