My ham website
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.

179 lines
7.8 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="/posts/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. <p>The accompanying repo for the code produced in this article is located
  19. <a href="https://github.com/leothelocust/basic-http-routing-in-golang">on github</a>.</p>
  20. <h3 id="step-1">Step 1</h3>
  21. <p>Here is our basic folder structure for this basic http routing example:</p>
  22. <pre><code> basic-http-routing-in-golang/
  23. main.go
  24. </code></pre>
  25. <p>As a starting point our
  26. <code>main.go</code> file looks like this:</p>
  27. <pre><code> package main
  28. import (
  29. &quot;fmt&quot;
  30. _ &quot;net/http&quot;
  31. )
  32. func main() {
  33. fmt.Println(&quot;Hello HTTP&quot;)
  34. }
  35. </code></pre>
  36. <h3 id="step-2">Step 2</h3>
  37. <p>Now starting at a very basic level, we can leverage the
  38. <a href="https://golang.org/pkg/net/http/#HandleFunc">
  39. <code>http.HandleFunc</code>
  40. </a> method.</p>
  41. <p>It is very simple to use and its signature is easy to understand.</p>
  42. <pre><code> func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
  43. </code></pre>
  44. <p>Which basically means,
  45. <code>http.HandleFunc(&quot;/url&quot;, routingFunction)</code> where
  46. <code>routingFunction</code> looks like this:</p>
  47. <pre><code> func routingFunction(w http.ResponseWriter, req *http.Request) {
  48. fmt.Fprint(w, &quot;Hello HTTP&quot;)
  49. }
  50. </code></pre>
  51. <p>With
  52. <code>fmt.Fprint()</code> we can pass an
  53. <code>http.ResponseWriter</code> and a message to display. Our browser will now look like this when we visit the
  54. <code>/url</code> endpoint.</p>
  55. <p>
  56. <img src="/images/step2-browser-output.png" alt="Browser Output for Step 2 - Hellp HTTP">
  57. </p>
  58. <p>Here is what
  59. <code>main.go</code> looks like at this point:</p>
  60. <pre><code> package main
  61. import (
  62. &quot;fmt&quot;
  63. &quot;log&quot;
  64. &quot;net/http&quot;
  65. )
  66. func main() {
  67. http.HandleFunc(&quot;/hello&quot;, helloHTTP)
  68. log.Fatal(http.ListenAndServe(&quot;:8080&quot;, nil))
  69. }
  70. func helloHTTP(w http.ResponseWriter, req *http.Request) {
  71. fmt.Fprint(w, &quot;Hello HTTP&quot;)
  72. }
  73. </code></pre>
  74. <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
  75. yet, until we start to see something slightly more practical.</p>
  76. <h3 id="step-3">Step 3</h3>
  77. <p>For starters, let's add a
  78. <code>NotFound</code> page when we don't match a pattern in
  79. <code>HandleFunc</code>.</p>
  80. <p>Here is what
  81. <code>main.go</code> looks like after that:</p>
  82. <pre><code> package main
  83. import (
  84. &quot;fmt&quot;
  85. &quot;log&quot;
  86. &quot;net/http&quot;
  87. )
  88. func main() {
  89. http.HandleFunc(&quot;/hello&quot;, helloHTTP)
  90. http.HandleFunc(&quot;/&quot;, notFound)
  91. log.Fatal(http.ListenAndServe(&quot;:8080&quot;, nil))
  92. }
  93. func helloHTTP(w http.ResponseWriter, req *http.Request) {
  94. fmt.Fprint(w, &quot;Hello HTTP&quot;)
  95. }
  96. func notFound(w http.ResponseWriter, req *http.Request) {
  97. http.NotFound(w, req)
  98. }
  99. </code></pre>
  100. <p>This will match
  101. <code>/hello</code> and use the
  102. <code>HelloHTTP</code> method to print &quot;Hello HTTP&quot; to the browser. Any other urls will get caught by the
  103. <code>/</code> pattern and be given the
  104. <code>http.NotFound</code> response to the browser.</p>
  105. <p>So that works, but I think we can go further.</p>
  106. <h3 id="step-4">Step 4</h3>
  107. <p>We need to give ourselves something more specific than the simple contrived
  108. <code>/hello</code> endpoint above. So let's assume we are needing to get a user profile and we will use the url
  109. <code>/user/:id</code> where
  110. <code>:id</code> is an identifier used to get the user profile from our persistance layer (i.e. our database).</p>
  111. <p>We'll start by creating a new method for this GET request called
  112. <code>userProfile</code>:</p>
  113. <pre><code> func userProfile(w http.ResponseWriter, req *http.Request) {
  114. userID := req.URL.Path[len(&quot;/user/&quot;):]
  115. fmt.Fprintf(w, &quot;User Profile: %q&quot;, userID)
  116. }
  117. </code></pre>
  118. <p>Notice that we get the URL from the
  119. <code>req</code> variable and we treat the string returned from
  120. <code>req.URL.Path</code> as a byte slice to get everything after the
  121. <code>/user/</code> in the string.
  122. <strong>Note: this isn't fool proof,
  123. <code>/user/10/ok</code> would get matched here, and we would be assigning
  124. <code>userID</code> to
  125. <code>&quot;10/ok&quot;</code>.</strong>
  126. </p>
  127. <p>And we'll add the new route in our
  128. <code>main</code> function:</p>
  129. <pre><code> func main() {
  130. http.HandleFunc(&quot;/hello&quot;, helloHTTP)
  131. http.HandleFunc(&quot;/user/&quot;, userProfile)
  132. http.HandleFunc(&quot;/&quot;, notFound)
  133. log.Fatal(http.ListenAndServe(&quot;:8080&quot;, nil))
  134. }
  135. </code></pre>
  136. <p>
  137. <em>Note: that this pattern
  138. <code>/user/</code> matches the trailing
  139. <code>/</code> so that a call to
  140. <code>/user</code> in the browser would return a
  141. <code>404 Not Found</code>.</em>
  142. </p>
  143. <h3 id="step-5">Step 5</h3>
  144. <p>Ok, so we have introduced some pretty severe holes in the security of our new HTTP router. As mentioned in a note above,
  145. treating the
  146. <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>
  147. <pre><code> var validPath = regexp.MustCompile(&quot;^/(user)/([0-9]+)$&quot;)
  148. func getID(w http.ResponseWriter, req *http.Request) (string, error) {
  149. m := validPath.FindStringSubmatch(req.URL.Path)
  150. if m == nil {
  151. http.NotFound(w, req)
  152. return &quot;&quot;, errors.New(&quot;Invalid ID&quot;)
  153. }
  154. return m[2], nil // The ID is the second subexpression.
  155. }
  156. </code></pre>
  157. <p>Now we can use this method in our code:</p>
  158. <pre><code> func userProfile(w http.ResponseWriter, req *http.Request) {
  159. userID, err := getID(w, req)
  160. if err != nil {
  161. return
  162. }
  163. fmt.Fprintf(w, &quot;User Profile: %q&quot;, userID)
  164. }
  165. </code></pre>
  166. <h2 id="conclusion">Conclusion</h2>
  167. <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.
  168. Additionally, I'd like to create a more advanced article that discusses the ability to respond to POST, PUT, and DELETE
  169. requests. Look for an &quot;Advanced HTTP routing in Golang&quot; article in the future. Thanks for reading this far.
  170. I wish you well in your Go endeavors.</p>