Merge api.go into main.go

It would be really painful to provide variables there
This commit is contained in:
Alexey Yerin 2021-01-18 22:52:33 +03:00
parent 4de54045cc
commit 1a32c713bc
2 changed files with 31 additions and 37 deletions

36
api.go
View File

@ -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))
}

32
main.go
View File

@ -17,6 +17,7 @@
package main package main
import ( import (
"fmt"
"html/template" "html/template"
"log" "log"
"net/http" "net/http"
@ -60,7 +61,31 @@ func main() {
tmpl.ExecuteTemplate(w, "index", indexPageData{from, to, text, translation}) tmpl.ExecuteTemplate(w, "index", indexPageData{from, to, text, translation})
}).Methods("GET", "POST") }).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 // Static files
fs := http.FileServer(http.Dir(*staticDir)) fs := http.FileServer(http.Dir(*staticDir))
@ -69,3 +94,8 @@ func main() {
log.Println("Starting on", *bind) log.Println("Starting on", *bind)
log.Fatalln(http.ListenAndServe(*bind, r)) log.Fatalln(http.ListenAndServe(*bind, r))
} }
func writeError(w http.ResponseWriter, status int, err interface{}) {
w.WriteHeader(status)
w.Write([]byte(fmt.Sprintln(err)))
}