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.

178 lines
7.7 KiB

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