Introduction
In the last post we discussed handling request parameters in go. In this post, we’ll go over handling RESTful methods and how to use them with our requests.
Setup
This is what our main.go
file looks like:
package main
import ( "fmt" "log" "net/http")
func main() { router := http.NewServeMux()
router.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("pong")) })
log.Fatal(http.ListenAndServe(":8080", router))}
We have a basic /ping
route that pong
s whenever we hit it. Let’s bind it to a method.
Handling RESTful Methods
ServeMux
handler from the net/http
package has built in features to handle RESTful Methods.
When defining the route, you simply append the relevant method right in the route pattern:
[METHOD] [HOST]/[PATH]
With all three parts being optional, and /
being a valid path. You can read more about this pattern here.
Let’s bind the /ping
route to a GET
method:
router.HandleFunc("GET /ping", func (w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "pong")})
And now to test it out:
iwr http://localhost:8080/ping -Method GET
HTTP/1.1 200 OKContent-Length: 4Content-Type: text/plain; charset=utf-8
pong
Great! This works as expected! Now, let’s try making a POST
request
iwr http://localhost:8080/ping -Method POST
HTTP/1.1 405 Method Not AllowedAllow: GET, HEADContent-Type: text/plain; charset=utf-8X-Content-Type-Options: nosniffContent-Length: 19
Method Not Allowed
You’ll notice it only allows the GET
and HEAD
requests to this route!
This binding also works with POST
, PUT
, UPDATE
, DELETE
, and even custom methods!
Let’s try using a POST
method instead of a GET
.
router.HandleFunc("POST /ping", func (w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "pong")})
Making the POST
request again, we get:
iwr http://localhost:8080/ping -Method POST
HTTP/1.1 200 OKContent-Length: 4Content-Type: text/plain; charset=utf-8
pong
PS: In case you’re wondering, the methods do need to be in all caps due the HTTP convention. All requests going out have their methods capitalized. Go assumes you’re following convention, and doesn’t automatically captialize the method you set.
And now you know how to handle request methods!