Skip to content

Instantly share code, notes, and snippets.

@yobayob
Created July 23, 2018 16:49
Show Gist options
  • Save yobayob/98ff223310310e7f29039c6f5d12683f to your computer and use it in GitHub Desktop.
Save yobayob/98ff223310310e7f29039c6f5d12683f to your computer and use it in GitHub Desktop.
package main
import (
"net/http"
"log"
"os"
"encoding/json"
)
type translateRequestSchema struct {
Text string
FromLang string `json:"from_lang"`
ToLang string `json:"to_lang"`
}
type translateResponseSchema struct {
Text string `json:"text"`
}
func translateText(text, from, to string) (string, error) {
return text, nil
}
func translateHandler(writer http.ResponseWriter, request *http.Request) {
var (
t translateRequestSchema
response []byte
)
// set content type
writer.Header().Set("Content-Type", "application/json")
// start decode request
decoder := json.NewDecoder(request.Body)
if err := decoder.Decode(&t); err != nil {
http.Error(writer, err.Error(), http.StatusBadRequest)
return
}
// translate text
text, err := translateText(t.Text, t.FromLang, t.ToLang)
var result = &translateResponseSchema{
Text: text,
}
if response, err = json.Marshal(result); err != nil{
http.Error(writer, err.Error(), http.StatusInternalServerError)
return
}
// result
writer.Write(response)
writer.WriteHeader(http.StatusOK)
return
}
func main() {
http.HandleFunc("/api/translate", translateHandler)
log.Printf("Start server on port 8080", )
// runserver
if err := http.ListenAndServe(":8000", nil); err != nil{
log.Println(err)
os.Exit(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment