A simple look at some basic ways of getting HTTP routing of GET requests in Go.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
904 B

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "regexp"
  8. )
  9. func main() {
  10. http.HandleFunc("/hello", helloHTTP)
  11. http.HandleFunc("/user/", userProfile)
  12. http.HandleFunc("/", notFound)
  13. log.Fatal(http.ListenAndServe(":8080", nil))
  14. }
  15. func helloHTTP(w http.ResponseWriter, req *http.Request) {
  16. fmt.Fprint(w, "Hello HTTP")
  17. }
  18. func notFound(w http.ResponseWriter, req *http.Request) {
  19. http.NotFound(w, req)
  20. }
  21. func userProfile(w http.ResponseWriter, req *http.Request) {
  22. userID, err := getID(w, req)
  23. if err != nil {
  24. return
  25. }
  26. fmt.Fprintf(w, "User Profile: %q", userID)
  27. }
  28. var validPath = regexp.MustCompile("^/(user)/([0-9]+)$")
  29. func getID(w http.ResponseWriter, req *http.Request) (string, error) {
  30. m := validPath.FindStringSubmatch(req.URL.Path)
  31. if m == nil {
  32. http.NotFound(w, req)
  33. return "", errors.New("Invalid ID")
  34. }
  35. return m[2], nil // The ID is the second subexpression.
  36. }