With `fmt.Fprint()` we can pass an `http.ResponseWriter` and a message to display. Our browser will now look like this when we visit the `/url` endpoint.
@ -54,22 +58,23 @@ With `fmt.Fprint()` we can pass an `http.ResponseWriter` and a message to displa
Here is what `main.go` looks like at this point:
package main
<preclass="prettyprint"><codeclass="language-go"> package main
Now we could stop there, as this is a "basic" http routing example, but I think it isn't quite useful as an example yet, until we start to see something slightly more practical.
@ -77,33 +82,35 @@ Now we could stop there, as this is a "basic" http routing example, but I think
So let's add a `NotFound` page when we don't match a pattern in `HandleFunc`. It's as simple as:
This will match `/hello` and use the `HelloHTTP` method to print "Hello HTTP" to the browser. Any other URLs will get caught by the `/` pattern and be given the `http.NotFound` response to the browser.
@ -115,21 +122,23 @@ We need to give ourselves something more specific than the simple contrived `/he
We'll start by creating a new method for this GET request called `userProfile`:
Notice that we get the URL from the `req` variable and we treat the string returned from `req.URL.Path` as a byte slice to get everything after the `/user/` in the string. **Note: this isn't fool proof, `/user/10ok` would get matched here, and we would be assigning `userID` to `"10ok"`.**
_Note: that this pattern `/user/` matches the trailing `/` so that a call to `/user` in the browser would return a `404 Not Found`._
@ -137,27 +146,29 @@ _Note: that this pattern `/user/` matches the trailing `/` so that a call to `/u
Ok, so we have introduced some pretty severe holes in the security of our new HTTP router. As mentioned in a note above, treating the `req.URL.Path` as a byte slice and just taking the last half is a terrible idea. So let's fix this:
var validPath = regexp.MustCompile("^/(user)/([0-9]+)$")
<preclass="prettyprint"><codeclass="language-go"> var validPath = regexp.MustCompile("^/(user)/([0-9]+)$")
For now, I'm calling this "Basic HTTP Routing in Golang" article finished. But I do plan to add more to it as time allows. Additionally, I'd like to create a more advanced article that discusses the ability to respond to not only GET requests, but also POST, PUT, and DELETE HTTP methods. Look for an "Advanced HTTP routing in Golang" article in the future. Thanks for reading this far. I wish you well in your Go endeavors.
For now, I'm calling this "Basic HTTP Routing in Golang" article finished. But I do plan to add more to it as time allows. Additionally, I'd like to create a more advanced article that discusses the ability to respond to not only GET requests, but also POST, PUT, and DELETE HTTP methods. Look for an "Advanced HTTP routing in Golang" article in the future. Thanks for reading this far. I wish you well in your Go endeavors.