Last active
July 23, 2018 12:41
-
-
Save fwojciec/8481d19cb1fde4896916214920fb56df to your computer and use it in GitHub Desktop.
My solution to "Exercise better errors" from Section 03 of Francesc Campoy's Go Web Workshop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://github.com/campoy/go-web-workshop/blob/master/section03/README.md | |
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"strings" | |
"github.com/gorilla/mux" | |
) | |
// type errorReader struct{} | |
// func (e errorReader) Read(p []byte) (n int, err error) { | |
// return 0, errors.New("test error") | |
// } | |
func bodyHandler(w http.ResponseWriter, r *http.Request) { | |
// b, err := ioutil.ReadAll(&errorReader{}) | |
b, err := ioutil.ReadAll(r.Body) | |
if err != nil { | |
w.WriteHeader(http.StatusInternalServerError) | |
fmt.Fprintln(w, "Internal Server Error") | |
return | |
} | |
name := strings.TrimSpace(string(b)) | |
if name == "" { | |
w.WriteHeader(http.StatusBadRequest) | |
fmt.Fprintln(w, "Bad Request") | |
return | |
} | |
fmt.Fprintf(w, "Hello, %s!", name) | |
} | |
func main() { | |
r := mux.NewRouter() | |
r.HandleFunc("/hello", bodyHandler) | |
http.Handle("/", r) | |
if err := http.ListenAndServe("127.0.0.1:8080", nil); err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment