Create and view
Context Path | Handler | Action | Method |
---|---|---|---|
/ |
home |
Home page | GET |
/view |
newsView |
View | GET |
/create |
create |
Create | POST |
Update main.go
:
main.go
package main
import (
"log"
"net/http"
)
func home(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("News Feeder - HOME"))
}
func newsView(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("News Feeder - READ"))
}
func newsCreate(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("News Feeder - CREATE"))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", home)
mux.HandleFunc("/view", newsView)
mux.HandleFunc("/create", newsCreate)
log.Print("starting server on :8080")
err := http.ListenAndServe(":8080", mux)
log.Fatal(err)
}
Go’s servemux supports two different types of URL patterns: fixed paths and subtree paths. Fixed paths don’t end with a trailing slash, whereas subtree paths do end with a trailing slash.
You can think of subtree paths as acting a bit like they have a wildcard at the end, like /**
or /static/**
, which helps explain why the /
pattern is acting like a catch-all.
To avoid this behavior, include the following code in the home
function:
Restrict Method
main.go
package main
import (
"log"
"net/http"
)
func home(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("News Feeder - HOME"))
}
func newsView(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("News Feeder - READ"))
}
func newsCreate(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.Header().Set("Allow", "POST")
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
w.Write([]byte("News Feeder - CREATE"))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", home)
mux.HandleFunc("/view", newsView)
mux.HandleFunc("/create", newsCreate)
log.Print("starting server on :8080")
err := http.ListenAndServe(":8080", mux)
log.Fatal(err)
}