ex2_hellogorilla.go 623 B

12345678910111213141516171819202122232425262728293031
  1. package main
  2. import (
  3. "net/http"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/gorilla/mux"
  7. )
  8. type API struct {
  9. Message string "json:message"
  10. }
  11. func Hello(w http.ResponseWriter, r *http.Request) {
  12. urlParams := mux.Vars(r)
  13. name := urlParams["user"]
  14. HelloMessage := "Hello, " + name
  15. message := API{Message:HelloMessage}
  16. output, err := json.Marshal(message)
  17. if err != nil {
  18. fmt.Println("Something went wrong", err)
  19. }
  20. fmt.Fprint(w, string(output))
  21. }
  22. func main() {
  23. gorillaRoute := mux.NewRouter()
  24. gorillaRoute.HandleFunc("/api/{user:[0-9]+}", Hello)
  25. http.Handle("/", gorillaRoute)
  26. http.ListenAndServe(":8080", nil)
  27. }