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.

177 lines
7.6 KiB

  1. <p>Golang is incredibly powerful. Its standard library has so much to offer, but I think other languages have encouraged the
  2. use of external libraries for even the most basic tasks. For example, with JavaScript, most inexperienced developers
  3. seem to use jQuery to do simple tasks like selecting an element and replacing its contents. When you and I both know
  4. jQuery is way overkill for such a task.
  5. <a href="/coming-soon">See my article on Vanilla JS basics.</a>.</p>
  6. <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
  7. language to achieve your goal. In our current case, HTTP routing. Now to be clear, I don't think you need to write everything
  8. from scratch all the time, but you should have a firm grasp on what is available by the core language, and when you are
  9. better suited to use an external library. If you are looking for more advanced HTTP routing, then I would suggest using
  10. something like
  11. <a href="https://github.com/gin-gonic/gin">gin</a>.</p>
  12. <p>Enough ranting, let's get to it.</p>
  13. <h2 id="assumptions">Assumptions</h2>
  14. <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
  15. level basics first. See
  16. <a href="https://tour.golang.org">A Tour of Go</a>.</p>
  17. <h2 id="lets-begin">Let's begin</h2>
  18. <h3 id="step-1">Step 1</h3>
  19. <p>Here is our basic folder structure for this basic http routing example:</p>
  20. <pre><code> basic-http-routing-in-golang/
  21. main.go
  22. </code></pre>
  23. <p>As a starting point our
  24. <code>main.go</code> file looks like this:</p>
  25. <pre><code> package main
  26. import (
  27. &quot;fmt&quot;
  28. _ &quot;net/http&quot;
  29. )
  30. func main() {
  31. fmt.Println(&quot;Hello HTTP&quot;)
  32. }
  33. </code></pre>
  34. <h3 id="step-2">Step 2</h3>
  35. <p>Now starting at a very basic level, we can leverage the
  36. <a href="https://golang.org/pkg/net/http/#HandleFunc">
  37. <code>http.HandleFunc</code>
  38. </a> method.</p>
  39. <p>It is very simple to use and its signature is easy to understand.</p>
  40. <pre><code> func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
  41. </code></pre>
  42. <p>Which basically means,
  43. <code>http.HandleFunc(&quot;/url&quot;, routingFunction)</code> where
  44. <code>routingFunction</code> looks like this:</p>
  45. <pre><code> func routingFunction(w http.ResponseWriter, req *http.Request) {
  46. fmt.Fprint(w, &quot;Hello HTTP&quot;)
  47. }
  48. </code></pre>
  49. <p>With
  50. <code>fmt.Fprint()</code> we can pass an
  51. <code>http.ResponseWriter</code> and a message to display. Our browser will now look like this when we visit the
  52. <code>/url</code> endpoint.</p>
  53. <p>
  54. <img src="file:///c%3A/Users/lolson/Projects/dev/levi/step2-browser-output.png" alt="Browser Output for Step 2 - Hellp HTTP">
  55. </p>
  56. <p>Here is what
  57. <code>main.go</code> looks like at this point:</p>
  58. <pre><code> package main
  59. import (
  60. &quot;fmt&quot;
  61. &quot;log&quot;
  62. &quot;net/http&quot;
  63. )
  64. func main() {
  65. http.HandleFunc(&quot;/hello&quot;, helloHTTP)
  66. log.Fatal(http.ListenAndServe(&quot;:8080&quot;, nil))
  67. }
  68. func helloHTTP(w http.ResponseWriter, req *http.Request) {
  69. fmt.Fprint(w, &quot;Hello HTTP&quot;)
  70. }
  71. </code></pre>
  72. <p>Now we could stop there, as this is a &quot;basic&quot; http routing example, but I think it isn't quite useful as an example
  73. yet, until we start to see something slightly more practical.</p>
  74. <h3 id="step-3">Step 3</h3>
  75. <p>For starters, let's add a
  76. <code>NotFound</code> page when we don't match a pattern in
  77. <code>HandleFunc</code>.</p>
  78. <p>Here is what
  79. <code>main.go</code> looks like after that:</p>
  80. <pre><code> package main
  81. import (
  82. &quot;fmt&quot;
  83. &quot;log&quot;
  84. &quot;net/http&quot;
  85. )
  86. func main() {
  87. http.HandleFunc(&quot;/hello&quot;, helloHTTP)
  88. http.HandleFunc(&quot;/&quot;, notFound)
  89. log.Fatal(http.ListenAndServe(&quot;:8080&quot;, nil))
  90. }
  91. func helloHTTP(w http.ResponseWriter, req *http.Request) {
  92. fmt.Fprint(w, &quot;Hello HTTP&quot;)
  93. }
  94. func notFound(w http.ResponseWriter, req *http.Request) {
  95. http.NotFound(w, req)
  96. }
  97. </code></pre>
  98. <p>This will match
  99. <code>/hello</code> and use the
  100. <code>HelloHTTP</code> method to print &quot;Hello HTTP&quot; to the browser. Any other urls will get caught by the
  101. <code>/</code> pattern and be given the
  102. <code>http.NotFound</code> response to the browser.</p>
  103. <p>So that works, but I think we can go further.</p>
  104. <h3 id="step-4">Step 4</h3>
  105. <p>We need to give ourselves something more specific than the simple contrived
  106. <code>/hello</code> endpoint above. So let's assume we are needing to get a user profile and we will use the url
  107. <code>/user/:id</code> where
  108. <code>:id</code> is an identifier used to get the user profile from our persistance layer (i.e. our database).</p>
  109. <p>We'll start by creating a new method for this GET request called
  110. <code>userProfile</code>:</p>
  111. <pre><code> func userProfile(w http.ResponseWriter, req *http.Request) {
  112. userID := req.URL.Path[len(&quot;/user/&quot;):]
  113. fmt.Fprintf(w, &quot;User Profile: %q&quot;, userID)
  114. }
  115. </code></pre>
  116. <p>Notice that we get the URL from the
  117. <code>req</code> variable and we treat the string returned from
  118. <code>req.URL.Path</code> as a byte slice to get everything after the
  119. <code>/user/</code> in the string.
  120. <strong>Note: this isn't fool proof,
  121. <code>/user/10/ok</code> would get matched here, and we would be assigning
  122. <code>userID</code> to
  123. <code>&quot;10/ok&quot;</code>.</strong>
  124. </p>
  125. <p>And we'll add the new route in our
  126. <code>main</code> function:</p>
  127. <pre><code> func main() {
  128. http.HandleFunc(&quot;/hello&quot;, helloHTTP)
  129. http.HandleFunc(&quot;/user/&quot;, userProfile)
  130. http.HandleFunc(&quot;/&quot;, notFound)
  131. log.Fatal(http.ListenAndServe(&quot;:8080&quot;, nil))
  132. }
  133. </code></pre>
  134. <p>
  135. <em>Note: that this pattern
  136. <code>/user/</code> matches the trailing
  137. <code>/</code> so that a call to
  138. <code>/user</code> in the browser would return a
  139. <code>404 Not Found</code>.</em>
  140. </p>
  141. <h3 id="step-5">Step 5</h3>
  142. <p>Ok, so we have introduced some pretty severe holes in the security of our new HTTP router. As mentioned in a note above,
  143. treating the
  144. <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>
  145. <pre><code> var validPath = regexp.MustCompile(&quot;^/(user)/([0-9]+)$&quot;)
  146. func getID(w http.ResponseWriter, req *http.Request) (string, error) {
  147. m := validPath.FindStringSubmatch(req.URL.Path)
  148. if m == nil {
  149. http.NotFound(w, req)
  150. return &quot;&quot;, errors.New(&quot;Invalid ID&quot;)
  151. }
  152. return m[2], nil // The ID is the second subexpression.
  153. }
  154. </code></pre>
  155. <p>Now we can use this method in our code:</p>
  156. <pre><code> func userProfile(w http.ResponseWriter, req *http.Request) {
  157. userID, err := getID(w, req)
  158. if err != nil {
  159. return
  160. }
  161. fmt.Fprintf(w, &quot;User Profile: %q&quot;, userID)
  162. }
  163. </code></pre>
  164. <h2 id="conclusion">Conclusion</h2>
  165. <p>For now, I'm calling this &quot;Basic HTTP Routing in Golang&quot; article finished. But I do plan to add more as time allows.
  166. Additionally, I'd like to create a more advanced article that discusses the ability to respond to POST, PUT, and DELETE
  167. requests. Look for an &quot;Advanced HTTP routing in Golang&quot; article in the future. Thanks for reading this far.
  168. I wish you well in your Go endeavors.</p>