Browse Source

Ch1 pp52-54 Hello world with Gorilla mux.

Frederic G. MARAND 8 years ago
parent
commit
12b3e4459a
1 changed files with 31 additions and 0 deletions
  1. 31 0
      ch1/ex2_hellogorilla.go

+ 31 - 0
ch1/ex2_hellogorilla.go

@@ -0,0 +1,31 @@
+package main
+
+import (
+	"net/http"
+	"encoding/json"
+	"fmt"
+	"github.com/gorilla/mux"
+)
+
+type API struct {
+	Message string "json:message"
+}
+
+func Hello(w http.ResponseWriter, r *http.Request) {
+	urlParams := mux.Vars(r)
+	name := urlParams["user"]
+	HelloMessage := "Hello, " + name
+	message := API{Message:HelloMessage}
+	output, err := json.Marshal(message)
+	if err != nil {
+		fmt.Println("Something went wrong", err)
+	}
+	fmt.Fprint(w, string(output))
+}
+
+func main() {
+	gorillaRoute := mux.NewRouter()
+	gorillaRoute.HandleFunc("/api/{user:[0-9]+}", Hello)
+	http.Handle("/", gorillaRoute)
+	http.ListenAndServe(":8080", nil)
+}