Created
July 23, 2018 12:41
-
-
Save fwojciec/26a9a75b22eb6cd30425e20b8da0140a to your computer and use it in GitHub Desktop.
My solution to "Exercise status codes with http.Error" 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 { | |
http.Error(w, "Internal Server Error", http.StatusInternalServerError) | |
return | |
} | |
name := strings.TrimSpace(string(b)) | |
if name == "" { | |
http.Error(w, "Bad Request", http.StatusBadRequest) | |
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