<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Mike Nithaworn</title>
    <description>The latest articles on DEV Community by Mike Nithaworn (@mnithaworn).</description>
    <link>https://dev.to/mnithaworn</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F395074%2Fe305c315-4cae-4744-b4f9-f8c69b9fe06a.jpeg</url>
      <title>DEV Community: Mike Nithaworn</title>
      <link>https://dev.to/mnithaworn</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/mnithaworn"/>
    <language>en</language>
    <item>
      <title>Golang net.http routing with mux</title>
      <dc:creator>Mike Nithaworn</dc:creator>
      <pubDate>Tue, 16 Jun 2020 18:19:41 +0000</pubDate>
      <link>https://dev.to/mnithaworn/golang-net-http-routing-with-mux-2436</link>
      <guid>https://dev.to/mnithaworn/golang-net-http-routing-with-mux-2436</guid>
      <description>&lt;h4&gt;How to Route Requests?&lt;/h4&gt;

&lt;p&gt;In order to route, we need a mux.  We also use the &lt;i&gt;Handle&lt;/i&gt; and &lt;i&gt;HandleFunc&lt;/i&gt; functions to setup a mux and allow routing URL paths to custom functions for data processing and responding.&lt;/p&gt;

&lt;p&gt;&lt;i&gt;Handle&lt;/i&gt; vs &lt;i&gt;HandleFunc&lt;/i&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;i&gt;Handle&lt;/i&gt; takes in a path string and any type that is a &lt;i&gt;Handler&lt;/i&gt;.  A &lt;i&gt;Handler&lt;/i&gt; is anything that implements &lt;i&gt;ServeHTTP&lt;/i&gt; with a &lt;i&gt;ResponseWriter&lt;/i&gt; and a pointer to a &lt;i&gt;Request&lt;/i&gt;.
&lt;/li&gt;
&lt;li&gt;
&lt;i&gt;HandleFunc&lt;/i&gt; takes in a path string and a function of any name with a &lt;i&gt;ResponseWriter&lt;/i&gt; and a pointer to a &lt;i&gt;Request&lt;/i&gt;.
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Both functions are available in the &lt;code&gt;http&lt;/code&gt; package and any custom mux created. Ideally we want to use &lt;i&gt;HandleFunc&lt;/i&gt; as it is the more elegant solution.&lt;/p&gt;

&lt;p&gt;Create a custom mux:&lt;/p&gt;

&lt;p&gt;The following creates a new mux and calls the mux's &lt;i&gt;HandleFunc&lt;/i&gt; function that takes in a string for the URL path and a custom function named &lt;i&gt;myFunc&lt;/i&gt; with &lt;i&gt;ResponseWriter&lt;/i&gt; and a pointer to a &lt;i&gt;Request&lt;/i&gt; as arguments.  It then uses the newly created &lt;i&gt;mux&lt;/i&gt; to listen on port 8080.&lt;/p&gt;

&lt;pre&gt;
&lt;code&gt;
func myFunc(res http.ResponseWriter, req *http.Request) {
  fmt.Fprintln(res, "Response from myFunc")
}

func main() {
  mux := http.NewServeMux()
  mux.HandleFunc("/path", myFunc)
  http.ListenAndServe(":8080", mux)
}
&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;Using the default mux:&lt;/p&gt;

&lt;p&gt;The following uses &lt;i&gt;HandleFunc&lt;/i&gt; from the &lt;code&gt;net.http&lt;/code&gt; package and takes in a string for the URL path and a custom function named &lt;i&gt;myFunc&lt;/i&gt; with &lt;i&gt;ResponseWriter&lt;/i&gt; and a pointer to a &lt;i&gt;Request&lt;/i&gt; as arguments.  It then uses the &lt;i&gt;DefaultServeMux&lt;/i&gt; to listen on port 8080.&lt;/p&gt;

&lt;pre&gt;
&lt;code&gt;
func myFunc(res http.ResponseWriter, req *http.Request) {
  fmt.Fprintln(res, "Response from myFunc")
}

func main() {
  http.HandleFunc("/path", myFunc)
  http.ListenAndServe(":8080", nil)
}
&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;In general it is advised to use the &lt;i&gt;DefaultServeMux&lt;/i&gt; unless you really need to create your own mux.&lt;/p&gt;

&lt;h4&gt;HandleFunc vs HandlerFunc?&lt;/h4&gt;

&lt;p&gt;One thing that can be confusing in the &lt;code&gt;net.http&lt;/code&gt; package is that there is a function called &lt;i&gt;HandleFunc&lt;/i&gt; which we previously talked about and &lt;i&gt;HandlerFunc&lt;/i&gt; (notice the "er") which hasn't been talked about yet.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;i&gt;HandleFunc&lt;/i&gt; takes a path and function that with a &lt;i&gt;ResponseWriter&lt;/i&gt; and a pointer to a &lt;i&gt;Request&lt;/i&gt;.
&lt;/li&gt;
&lt;li&gt;
&lt;i&gt;HandlerFunc&lt;/i&gt; takes a path and a function and converts that function into a &lt;i&gt;Handler&lt;/i&gt;.
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Feel free to leave any comments and feedback.&lt;/p&gt;

</description>
      <category>go</category>
      <category>http</category>
      <category>tcp</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Golang net.http handling request/responses</title>
      <dc:creator>Mike Nithaworn</dc:creator>
      <pubDate>Tue, 26 May 2020 18:14:01 +0000</pubDate>
      <link>https://dev.to/mnithaworn/golang-net-http-handling-request-responses-46f9</link>
      <guid>https://dev.to/mnithaworn/golang-net-http-handling-request-responses-46f9</guid>
      <description>&lt;h4&gt;Introduction&lt;/h4&gt;

&lt;p&gt;In this post, I want to go over what I've learnt in studying how to create a web server that listens on a TCP network that handles client-server request/responses.  Here I will discuss Golang's &lt;i&gt;Handler&lt;/i&gt; from the &lt;i&gt;net.http&lt;/i&gt; package and how it is used to achieve this.&lt;/p&gt;

&lt;h4&gt;What is an Interface?&lt;/h4&gt;

&lt;p&gt;An interface is a type that defines functionality&lt;/p&gt;

&lt;h4&gt;What is a &lt;i&gt;Handler&lt;/i&gt;?&lt;/h4&gt;

&lt;p&gt;In order to process requests and responses on a network we need a &lt;i&gt;Handler&lt;/i&gt;.&lt;/p&gt;

&lt;p&gt;A &lt;i&gt;Handler&lt;/i&gt; is an interface and anything that implements &lt;i&gt;ServeHTTP&lt;/i&gt; is implicity a &lt;i&gt;Handler&lt;/i&gt; as well.&lt;/p&gt;

&lt;p&gt;Take a look at the following from the &lt;i&gt;http.Handler&lt;/i&gt; interface:&lt;/p&gt;

&lt;pre&gt;
&lt;code&gt;
type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}
&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;Here we have a function &lt;i&gt;ServeHTTP&lt;/i&gt; that takes in a &lt;i&gt;ResponseWriter&lt;/i&gt; and a pointer to a &lt;i&gt;Request&lt;/i&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;i&gt;Request&lt;/i&gt; is a pointer to a struct that contains all the data needed to process the request.
&lt;/li&gt;
&lt;li&gt;
&lt;i&gt;ResponseWriter&lt;/i&gt; allows us to set headers and send response text back to the client.
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
&lt;b&gt;Bottom line:&lt;/b&gt; A &lt;i&gt;Handler&lt;/i&gt; is type that has a &lt;i&gt;ServeHTTP&lt;/i&gt; function that takes in a &lt;i&gt;ResponseWriter&lt;/i&gt; and a pointer to a &lt;i&gt;Request&lt;/i&gt;.
&lt;/p&gt;

&lt;p&gt;As mentioned before, anything that implements &lt;i&gt;ServeHTTP&lt;/i&gt; would be a &lt;i&gt;Handler&lt;/i&gt; as well.  This allows for polymorphism where different types can be passed in anywhere a &lt;i&gt;Handler&lt;/i&gt; is required.  In particular, the &lt;i&gt;http.ListenAndServe&lt;/i&gt; function that listens and serves incoming requests is an example of this.&lt;/p&gt;

&lt;h4&gt;How to Use a &lt;i&gt;Handler?&lt;/i&gt;
&lt;/h4&gt;

&lt;p&gt;The &lt;i&gt;ListenAndServe&lt;/i&gt; function requires an address string and a &lt;i&gt;Handler&lt;/i&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;
http.ListenAndServe

func ListenAndServe(addr string, handler Handler) error
&lt;/code&gt;&lt;/pre&gt;

To paraphrase the Golang documentation, the &lt;i&gt;ListenAndServe&lt;/i&gt; function listens on the TCP network address &lt;i&gt;addr&lt;/i&gt; and makes a call to Serve with &lt;i&gt;handler&lt;/i&gt; to handle requests on incoming connections.

Generally the handler is &lt;code&gt;nil&lt;/code&gt;, and the &lt;i&gt;DefaultServeMux&lt;/i&gt; is used:

&lt;pre&gt;
&lt;code&gt;
http.ListenAndServe(":8080", nil)
&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;The following tells the &lt;i&gt;ListenAndServe&lt;/i&gt; function to listen on port 8080 using the &lt;i&gt;DefaultServeMux&lt;/i&gt;.&lt;/p&gt;

&lt;p&gt;A mux in laymen's terms is a data multiplexer that provides routing for incoming and outgoing traffic.  It is responsible for deciding where the data should go and what to do with it.  The mux is essentially responsible for URL routing and processing GET and POST requests.  More to be talked about in a future post.&lt;/p&gt;

&lt;p&gt;Although not a common practice, you can also pass in a custom handler as long as the type implements a &lt;i&gt;Handler&lt;/i&gt;.  But most of the times, the &lt;i&gt;DefaultServeMux&lt;/i&gt; is usually sufficient.&lt;/p&gt;

&lt;h4&gt;How to Process a Request?&lt;/h4&gt;

&lt;p&gt;The second argument of a &lt;i&gt;Handler&lt;/i&gt; is a &lt;i&gt;Request&lt;/i&gt;.  A &lt;i&gt;Request&lt;/i&gt; is a struct with many fields such as Method, URL, Form, PostForm, and etc.  It is here where we can extract request data and determine which functions to call to process the request.&lt;/p&gt;

&lt;p&gt;When working with a POST request, &lt;i&gt;Request&lt;/i&gt; has fields that allow for accessing form data:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;i&gt;Form&lt;/i&gt; gets data from both the URL query string and form data
&lt;/li&gt;
&lt;li&gt;
&lt;i&gt;PostForm&lt;/i&gt; gets data from form data only
&lt;/li&gt;
&lt;li&gt;
&lt;i&gt;FormValue&lt;/i&gt; is a helper function to get the value from a given name
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;i&gt;Form&lt;/i&gt; and &lt;i&gt;PostForm&lt;/i&gt; fields are only available after &lt;i&gt;ParseFrom&lt;/i&gt; is called.&lt;/p&gt;

&lt;p&gt;&lt;i&gt;http.ParseForm&lt;/i&gt; is a function that has a pointer reference to a &lt;i&gt;Request&lt;/i&gt;&lt;/p&gt;

&lt;p&gt;Example on how to call &lt;i&gt;ParseForm&lt;/i&gt;:&lt;/p&gt;

&lt;pre&gt;
&lt;code&gt;
func (m myHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
  err := req.ParseForm()
  if err != nil {
    log.Println(err)
  }
}
&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;After calling &lt;i&gt;ParseForm&lt;/i&gt;, accessing the &lt;i&gt;Form&lt;/i&gt; or &lt;i&gt;PostForm&lt;/i&gt; will return &lt;i&gt;url.Values&lt;/i&gt;.  &lt;i&gt;url.Values&lt;/i&gt; is a map that takes a string and returns a slice of strings.  The returned value will be a series of key-value pairs from the form data being sent.&lt;/p&gt;

&lt;h4&gt;How to Send Back a Response?&lt;/h4&gt;

&lt;p&gt;The &lt;i&gt;ResponseWriter&lt;/i&gt; will be used to send responses back to the client.  A&lt;br&gt;
&lt;i&gt;ResponseWriter&lt;/i&gt; is an interface that has a &lt;i&gt;Header&lt;/i&gt;.  Use the &lt;i&gt;Header&lt;/i&gt; to set values for the response such as &lt;code&gt;Content-Type&lt;/code&gt; and etc.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;res.Header().Set("Content-Type", "text/html; charset=utf-8")&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;From there, you can then finish off processing the response by passing in the &lt;i&gt;ResponseWriter&lt;/i&gt; to another function that will write and send back to the client.  If templates are being used, the code can look like this:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;tpl.ExecuteTemplate(res, "mypage.gohtml", data)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The following are other types of responses that can be done:&lt;/p&gt;

&lt;p&gt;HTML&lt;/p&gt;

&lt;pre&gt;
&lt;code&gt;
res.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintln(res, "Put html code in here")
&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;Text&lt;/p&gt;

&lt;pre&gt;
&lt;code&gt;
res.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintln(res, "This is some text")
&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;JSON&lt;/p&gt;

&lt;pre&gt;
&lt;code&gt;
res.Header().Set("Content-Type", "text/json; charset=utf-8")
fmt.Fprintln(res, "{\"item\": \"value\"}")
&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;Additionally you may need to use &lt;code&gt;json.Marshal(data)&lt;/code&gt; from the &lt;i&gt;json&lt;/i&gt; package when dealing with large data sets rather than hard-coding like the above example.&lt;/p&gt;

&lt;p&gt;This post is still in the works and will continually get updated.  Hit me up with any comments and feedback.  Peace.&lt;/p&gt;

</description>
      <category>go</category>
      <category>http</category>
      <category>tcp</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
