Created
July 23, 2018 12:02
-
-
Save fwojciec/e1454453d68d8c73fc258b7b72d2acc3 to your computer and use it in GitHub Desktop.
My solution to "Exercise Hello, body" 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" | |
) | |
func bodyHandler(w http.ResponseWriter, r *http.Request) { | |
b, err := ioutil.ReadAll(r.Body) | |
if err != nil { | |
fmt.Fprintf(w, "could not read body: %v", err) | |
return | |
} | |
name := strings.TrimSpace(string(b)) | |
if name == "" { | |
name = "friend" | |
} | |
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