My personal website https://leviolson.com
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.

128 lines
7.9 KiB

  1. <h1 id="basichttproutingingolang">Basic HTTP Routing in Golang</h1>
  2. <p>Golang is incredibly powerful. Its standard library has so much to offer, but I think other languages have encouraged the use of external libraries for even the most basic tasks. For example, with JavaScript, most inexperienced developers seem to use jQuery to do simple tasks like selecting an element and replacing its contents. When you and I both know jQuery is way overkill for such a task. <a href="https://leviolson.com/posts/vanilla-js-basics">See my article on Vanilla JS basics</a>.</p>
  3. <p>I believe that in order to be considered an expert in a language, you must at least be able to demonstrate using the core language to achieve your goal. In our current case, HTTP routing. Now to be clear, I don't think you need to write everything from scratch all the time, but you should have a firm grasp on what is available by the core language, and when you are better suited to use an external library. If you are looking for more advanced HTTP routing, then I would suggest using something like <a href="https://github.com/gin-gonic/gin">gin</a>.</p>
  4. <p>Enough ranting, let's get to it.</p>
  5. <h2 id="assumptions">Assumptions</h2>
  6. <p>I assume you have basic knowledge of the Go language at this point, so if not, it might be worth searching for some entry level basics first. See <a href="https://tour.golang.org">A Tour of Go</a>.</p>
  7. <h2 id="letsbegin">Let's begin</h2>
  8. <p>The accompanying repo for the code produced in this article is located <a href="https://github.com/leothelocust/basic-http-routing-in-golang">on github</a>.</p>
  9. <h3 id="step1">Step 1</h3>
  10. <p>Here is our basic folder structure for this basic http routing example:</p>
  11. <pre><code> basic-http-routing-in-golang/
  12. main.go
  13. </code></pre>
  14. <p>As a starting point our <code>main.go</code> file looks like this:</p>
  15. <pre class="prettyprint"><code> package main
  16. import (
  17. "fmt"
  18. _ "net/http"
  19. )
  20. func main() {
  21. fmt.Println("Hello HTTP")
  22. }
  23. </code></pre>
  24. <h3 id="step2">Step 2</h3>
  25. <p>Now starting at a very basic level, we can leverage the <a href="https://golang.org/pkg/net/http/#HandleFunc"><code>http.HandleFunc</code></a> method.</p>
  26. <p>It is very simple to use and its signature is easy to understand.</p>
  27. <pre class="prettyprint"><code class="language-go"> func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
  28. </code></pre>
  29. <p>Which basically means, <code class="prettyprint">http.HandleFunc("/url", routingFunction)</code> where <code>routingFunction</code> looks like this:</p>
  30. <pre class="prettyprint"><code class="language-go"> func routingFunction(w http.ResponseWriter, req *http.Request) {
  31. fmt.Fprint(w, "Hello HTTP")
  32. }
  33. </code></pre>
  34. <p>With <code>fmt.Fprint()</code> we can pass an <code>http.ResponseWriter</code> and a message to display. Our browser will now look like this when we visit the <code>/url</code> endpoint.</p>
  35. <p><img src="https://leviolson.com/images/step2-browser-output.png" alt="Browser Output for Step 2 - Hello HTTP" /></p>
  36. <p>Here is what <code>main.go</code> looks like at this point:</p>
  37. <pre class="prettyprint"><code class="language-go"> package main
  38. import (
  39. "fmt"
  40. "log"
  41. "net/http"
  42. )
  43. func main() {
  44. http.HandleFunc("/hello", helloHTTP)
  45. log.Fatal(http.ListenAndServe(":8080", nil))
  46. }
  47. func helloHTTP(w http.ResponseWriter, req *http.Request) {
  48. fmt.Fprint(w, "Hello HTTP")
  49. }
  50. </code></pre>
  51. <p>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.</p>
  52. <h3 id="step3">Step 3</h3>
  53. <p>So let's add a <code>NotFound</code> page when we don't match a pattern in <code>HandleFunc</code>. It's as simple as:</p>
  54. <pre class="prettyprint"><code class="language-go"> func notFound(w http.ResponseWriter, req *http.Request) {
  55. http.NotFound(w, req)
  56. }
  57. </code></pre>
  58. <p>Here is what <code>main.go</code> looks like after that:</p>
  59. <pre class="prettyprint"><code class="language-go"> package main
  60. import (
  61. "fmt"
  62. "log"
  63. "net/http"
  64. )
  65. func main() {
  66. http.HandleFunc("/hello", helloHTTP)
  67. http.HandleFunc("/", notFound)
  68. log.Fatal(http.ListenAndServe(":8080", nil))
  69. }
  70. func helloHTTP(w http.ResponseWriter, req *http.Request) {
  71. fmt.Fprint(w, "Hello HTTP")
  72. }
  73. func notFound(w http.ResponseWriter, req *http.Request) {
  74. http.NotFound(w, req)
  75. }
  76. </code></pre>
  77. <p>This will match <code>/hello</code> and use the <code>HelloHTTP</code> method to print "Hello HTTP" to the browser. Any other URLs will get caught by the <code>/</code> pattern and be given the <code>http.NotFound</code> response to the browser.</p>
  78. <p>So that works, but I think we can go further.</p>
  79. <h3 id="step4">Step 4</h3>
  80. <p>We need to give ourselves something more specific than the simple contrived <code>/hello</code> endpoint above. So let's assume we are needing to get a user profile. We will use the url <code>/user/:id</code> where <code>:id</code> is an identifier used to get the user profile from our persistance layer (i.e. our database).</p>
  81. <p>We'll start by creating a new method for this GET request called <code>userProfile</code>:</p>
  82. <pre class="prettyprint"><code class="language-go"> func userProfile(w http.ResponseWriter, req *http.Request) {
  83. userID := req.URL.Path[len("/user/"):]
  84. fmt.Fprintf(w, "User Profile: %q", userID)
  85. }
  86. </code></pre>
  87. <p>Notice that we get the URL from the <code>req</code> variable and we treat the string returned from <code>req.URL.Path</code> as a byte slice to get everything after the <code>/user/</code> in the string. <strong>Note: this isn't fool proof, <code>/user/10ok</code> would get matched here, and we would be assigning <code>userID</code> to <code>"10ok"</code>.</strong></p>
  88. <p>Let's add this new route in our <code>main</code> function:</p>
  89. <pre class="prettyprint"><code class="language-go"> func main() {
  90. http.HandleFunc("/hello", helloHTTP)
  91. http.HandleFunc("/user/", userProfile)
  92. http.HandleFunc("/", notFound)
  93. log.Fatal(http.ListenAndServe(":8080", nil))
  94. }
  95. </code></pre>
  96. <p><em>Note: that this pattern <code>/user/</code> matches the trailing <code>/</code> so that a call to <code>/user</code> in the browser would return a <code>404 Not Found</code>.</em></p>
  97. <h3 id="step5">Step 5</h3>
  98. <p>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 <code>req.URL.Path</code> as a byte slice and just taking the last half is a terrible idea. So let's fix this:</p>
  99. <pre class="prettyprint"><code class="language-go"> var validPath = regexp.MustCompile("^/(user)/([0-9]+)$")
  100. func getID(w http.ResponseWriter, req *http.Request) (string, error) {
  101. m := validPath.FindStringSubmatch(req.URL.Path)
  102. if m == nil {
  103. http.NotFound(w, req)
  104. return "", errors.New("Invalid ID")
  105. }
  106. return m[2], nil // The ID is the second subexpression.
  107. }
  108. </code></pre>
  109. <p>Now we can use this method in our code:</p>
  110. <pre class="prettyprint"><code class="language-go"> func userProfile(w http.ResponseWriter, req *http.Request) {
  111. userID, err := getID(w, req)
  112. if err != nil {
  113. return
  114. }
  115. fmt.Fprintf(w, "User Profile: %q", userID)
  116. }
  117. </code></pre>
  118. <h2 id="conclusion">Conclusion</h2>
  119. <p>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.</p>