Skip to content

Instantly share code, notes, and snippets.

@antklim
Last active November 25, 2020 03:36
Show Gist options
  • Select an option

  • Save antklim/93b69058751cafb317920494354b85a1 to your computer and use it in GitHub Desktop.

Select an option

Save antklim/93b69058751cafb317920494354b85a1 to your computer and use it in GitHub Desktop.
func notFoundHandler(w http.ResponseWriter, r *http.Request) {
writeRawBody(w, r, notFoundResponse, http.StatusNotFound)
}
func doHandler() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req Request
if err := unmarshalBody(r, &req); err != nil {
log.Println(err)
response := NewErrorResponse(err)
writeBody(w, r, response, http.StatusBadRequest)
return
}
if err := req.Validate(); err != nil {
log.Println(err)
response := NewErrorResponse(err)
writeBody(w, r, response, http.StatusUnprocessableEntity)
return
}
operation := Operations[req.Operation]
result := Do(operation.lambda, req.Arguments)
response := Response{
Operation: req.Operation,
Arguments: req.Arguments,
Result: result,
}
writeBody(w, r, response, http.StatusOK)
})
}
func remoteHandler(client HTTPClient) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
url := r.URL.Query().Get("url")
if url == "" {
url = "http://example.com/"
}
req, err := http.NewRequest(http.MethodPost, url, r.Body)
if err != nil {
log.Println(err)
response := NewErrorResponse(err)
writeBody(w, r, response, http.StatusInternalServerError)
return
}
res, err := client.Do(req)
if err != nil {
log.Println(err)
response := NewErrorResponse(err)
writeBody(w, r, response, http.StatusInternalServerError)
return
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
err := fmt.Errorf("remote call failed, returned status code %d", res.StatusCode)
log.Println(err)
response := NewErrorResponse(err)
writeBody(w, r, response, http.StatusInternalServerError)
return
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Println(err)
response := NewErrorResponse(err)
writeBody(w, r, response, http.StatusInternalServerError)
return
}
writeRawBody(w, req, body, http.StatusOK)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment