Skip to content

Instantly share code, notes, and snippets.

@fwojciec
Created July 23, 2018 12:02
Show Gist options
  • Save fwojciec/e1454453d68d8c73fc258b7b72d2acc3 to your computer and use it in GitHub Desktop.
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
// 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