<?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: TekniksMila</title>
    <description>The latest articles on DEV Community by TekniksMila (@josephokumu).</description>
    <link>https://dev.to/josephokumu</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%2F1238746%2F0df68702-03b9-4f6b-9a38-82caaeec5c4b.jpeg</url>
      <title>DEV Community: TekniksMila</title>
      <link>https://dev.to/josephokumu</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/josephokumu"/>
    <language>en</language>
    <item>
      <title>Building a Web Server in Go</title>
      <dc:creator>TekniksMila</dc:creator>
      <pubDate>Mon, 04 Mar 2024 19:24:26 +0000</pubDate>
      <link>https://dev.to/josephokumu/building-a-web-server-in-go-2onk</link>
      <guid>https://dev.to/josephokumu/building-a-web-server-in-go-2onk</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;A server is a specialized system whose role is to respond to requests made by computers over a network. Servers are very critical since they provide hosting for websites and applications, and they also facilitate communication over a network. In this article, let's dive into creating a simple HTTP server that serves files and handles form submissions and requests to specific endpoints.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Prerequisite:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Basic understanding of Go and web development concepts.&lt;/li&gt;
&lt;li&gt;Must have Go installed. If you do not have Go installed, first navigate here &lt;a href="https://go.dev/doc/manage-install" rel="noopener noreferrer"&gt;&lt;/a&gt; to install Go.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Project directory structure
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Open terminal.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create a directory with the name 'WebServer'.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Navigate into the 'WebServer' directory.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Initialize a new Go module.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create a file with the name 'main.go'.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create a new directory inside the 'WebServer' directory and name it 'files'.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Navigate into the files directory.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create two files with the names index.html and form.html.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt; &lt;span class="nb"&gt;mkdir &lt;/span&gt;WebServer
 &lt;span class="nb"&gt;cd &lt;/span&gt;WebServer
 go mod init example/WebServer
 &lt;span class="nb"&gt;touch &lt;/span&gt;main.go
 &lt;span class="nb"&gt;mkdir &lt;/span&gt;files
 &lt;span class="nb"&gt;cd &lt;/span&gt;files
 &lt;span class="nb"&gt;touch &lt;/span&gt;index.html
 &lt;span class="nb"&gt;touch &lt;/span&gt;form.html

&lt;span class="sb"&gt;```&lt;/span&gt;
&lt;span class="c"&gt;## The code&lt;/span&gt;
&lt;span class="k"&gt;*&lt;/span&gt; Open the index.html file and write the code as shown below. This will display a static web page.

&lt;span class="sb"&gt;````&lt;/span&gt;html
  &amp;lt;html&amp;gt;
      &amp;lt;&lt;span class="nb"&gt;head&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
          &amp;lt;title&amp;gt;static website&amp;lt;/title&amp;gt;        
      &amp;lt;/head&amp;gt;
      &amp;lt;body&amp;gt;
          &amp;lt;h2&amp;gt;static website&amp;lt;/h2&amp;gt;
      &amp;lt;/body&amp;gt;
  &amp;lt;/html&amp;gt;

&lt;span class="sb"&gt;```&lt;/span&gt;
&lt;span class="k"&gt;*&lt;/span&gt; Open the form.html file and write the code as shown below: When rendered, this will display a form with name and address text fields.

&lt;span class="sb"&gt;````&lt;/span&gt;html
  &amp;lt;&lt;span class="o"&gt;!&lt;/span&gt;DOCTYPE html&amp;gt;
  &amp;lt;html&amp;gt;
      &amp;lt;&lt;span class="nb"&gt;head&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
          &amp;lt;meta charset &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"UTF-8"&lt;/span&gt;/&amp;gt;
      &amp;lt;/head&amp;gt;
      &amp;lt;body&amp;gt;
          &amp;lt;div&amp;gt;
              &amp;lt;form &lt;span class="nv"&gt;method&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"POST"&lt;/span&gt; &lt;span class="nv"&gt;action&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"/form"&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
              &amp;lt;label&amp;gt;Name&amp;lt;/label&amp;gt;&amp;lt;input &lt;span class="nv"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"name"&lt;/span&gt; &lt;span class="nb"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"text"&lt;/span&gt; &lt;span class="nv"&gt;value&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;""&lt;/span&gt;/&amp;gt;
              &amp;lt;label&amp;gt;Address&amp;lt;/label&amp;gt;&amp;lt;input &lt;span class="nv"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"address"&lt;/span&gt; &lt;span class="nb"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"text"&lt;/span&gt; &lt;span class="nv"&gt;value&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;""&lt;/span&gt;/&amp;gt;

              &amp;lt;input &lt;span class="nb"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"submit"&lt;/span&gt; &lt;span class="nv"&gt;value&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"submit"&lt;/span&gt;/&amp;gt;
              &amp;lt;/form&amp;gt;
          &amp;lt;/div&amp;gt;
      &amp;lt;/body&amp;gt;
  &amp;lt;/html&amp;gt;

&lt;span class="sb"&gt;```&lt;/span&gt;
&lt;span class="k"&gt;*&lt;/span&gt; Open main.go. Here we start off by declaring the main package, &lt;span class="k"&gt;then &lt;/span&gt;import the packages that are necessary &lt;span class="k"&gt;for &lt;/span&gt;the working of our program.

&lt;span class="sb"&gt;````&lt;/span&gt;go
  package main

  import &lt;span class="o"&gt;(&lt;/span&gt;
      &lt;span class="s2"&gt;"fmt"&lt;/span&gt;
      &lt;span class="s2"&gt;"log"&lt;/span&gt;      // Importing the log package &lt;span class="k"&gt;for &lt;/span&gt;logging
      &lt;span class="s2"&gt;"net/http"&lt;/span&gt; // Importing the net/http package &lt;span class="k"&gt;for &lt;/span&gt;HTTP server functionality
  &lt;span class="o"&gt;)&lt;/span&gt;

&lt;span class="sb"&gt;````&lt;/span&gt;go
&lt;span class="k"&gt;*&lt;/span&gt; Next we create a &lt;span class="k"&gt;function &lt;/span&gt;that handles form submissions.

&lt;span class="sb"&gt;`````&lt;/span&gt;go
func formHandler&lt;span class="o"&gt;(&lt;/span&gt;w http.ResponseWriter, r &lt;span class="k"&gt;*&lt;/span&gt;http.Request&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    // ParseForm parses the raw query from the URL and updates r.Form
    &lt;span class="k"&gt;if &lt;/span&gt;err :&lt;span class="o"&gt;=&lt;/span&gt; r.ParseForm&lt;span class="o"&gt;()&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; err &lt;span class="o"&gt;!=&lt;/span&gt; nil &lt;span class="o"&gt;{&lt;/span&gt;
        fmt.Fprintf&lt;span class="o"&gt;(&lt;/span&gt;w, &lt;span class="s2"&gt;"ParseForm() err: %v"&lt;/span&gt;, err&lt;span class="o"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
    fmt.Fprintf&lt;span class="o"&gt;(&lt;/span&gt;w, &lt;span class="s2"&gt;"POST request successful"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    name :&lt;span class="o"&gt;=&lt;/span&gt; r.FormValue&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"name"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;               // Retrieve the value of the &lt;span class="s1"&gt;'name'&lt;/span&gt; parameter from the form
    address :&lt;span class="o"&gt;=&lt;/span&gt; r.FormValue&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"address"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;         // Retrieve the value of the &lt;span class="s1"&gt;'address'&lt;/span&gt; parameter from the form
    fmt.Fprintf&lt;span class="o"&gt;(&lt;/span&gt;w, &lt;span class="s2"&gt;"Name = %s&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;, name&lt;span class="o"&gt;)&lt;/span&gt;       // Print the name to the response writer
    fmt.Fprintf&lt;span class="o"&gt;(&lt;/span&gt;w, &lt;span class="s2"&gt;"Address = %s&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;, address&lt;span class="o"&gt;)&lt;/span&gt; // Print the address to the response writer
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="sb"&gt;```&lt;/span&gt;
&lt;span class="k"&gt;*&lt;/span&gt; Create a &lt;span class="k"&gt;function &lt;/span&gt;that handles requests to the /hello endpoint.

&lt;span class="sb"&gt;````&lt;/span&gt;go
func helloHandler&lt;span class="o"&gt;(&lt;/span&gt;w http.ResponseWriter, r &lt;span class="k"&gt;*&lt;/span&gt;http.Request&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if &lt;/span&gt;r.URL.Path &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="s2"&gt;"/hello"&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        http.Error&lt;span class="o"&gt;(&lt;/span&gt;w, &lt;span class="s2"&gt;"404 not found"&lt;/span&gt;, http.StatusNotFound&lt;span class="o"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;if &lt;/span&gt;r.Method &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="s2"&gt;"GET"&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        http.Error&lt;span class="o"&gt;(&lt;/span&gt;w, &lt;span class="s2"&gt;"method is not supported"&lt;/span&gt;, http.StatusNotFound&lt;span class="o"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
    fmt.Fprintf&lt;span class="o"&gt;(&lt;/span&gt;w, &lt;span class="s2"&gt;"hello!"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; // Respond with &lt;span class="s2"&gt;"hello!"&lt;/span&gt; &lt;span class="k"&gt;for &lt;/span&gt;GET requests to /hello endpoint
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="sb"&gt;```&lt;/span&gt;
&lt;span class="k"&gt;*&lt;/span&gt; Create a main &lt;span class="k"&gt;function &lt;/span&gt;that defines a simple HTTP server that serves static files from the ./files directory and handles requests to specific endpoints &lt;span class="o"&gt;(&lt;/span&gt;/form and /hello&lt;span class="o"&gt;)&lt;/span&gt; with custom handler functions.

&lt;span class="sb"&gt;````&lt;/span&gt;go
func main&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    fileServer :&lt;span class="o"&gt;=&lt;/span&gt; http.FileServer&lt;span class="o"&gt;(&lt;/span&gt;http.Dir&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"./files"&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt;
    // Create a file server handler &lt;span class="k"&gt;for &lt;/span&gt;serving static files from ./files directory
    http.Handle&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/"&lt;/span&gt;, fileServer&lt;span class="o"&gt;)&lt;/span&gt;            // Handle requests to root path with fileServer handler
    http.HandleFunc&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/form"&lt;/span&gt;, formHandler&lt;span class="o"&gt;)&lt;/span&gt;   // Handle requests to /form endpoint with formHandler &lt;span class="k"&gt;function
    &lt;/span&gt;http.HandleFunc&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/hello"&lt;/span&gt;, helloHandler&lt;span class="o"&gt;)&lt;/span&gt; // Handle requests to /hello endpoint with helloHandler &lt;span class="k"&gt;function

    &lt;/span&gt;fmt.Printf&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Starting server at port 8080&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;if &lt;/span&gt;err :&lt;span class="o"&gt;=&lt;/span&gt; http.ListenAndServe&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;":8080"&lt;/span&gt;, nil&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; err &lt;span class="o"&gt;!=&lt;/span&gt; nil &lt;span class="o"&gt;{&lt;/span&gt;
        log.Fatal&lt;span class="o"&gt;(&lt;/span&gt;err&lt;span class="o"&gt;)&lt;/span&gt; // Log any errors that occur during server startup and &lt;span class="nb"&gt;exit &lt;/span&gt;with error status
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="sb"&gt;```&lt;/span&gt;
&lt;span class="c"&gt;## Executing the program&lt;/span&gt;
&lt;span class="k"&gt;*&lt;/span&gt; Save the files you have created.

&lt;span class="k"&gt;*&lt;/span&gt; On the terminal &lt;span class="nb"&gt;type &lt;/span&gt;the following &lt;span class="nb"&gt;command&lt;/span&gt;:

&lt;span class="sb"&gt;````&lt;/span&gt;bash
go run main.go

&lt;span class="sb"&gt;```&lt;/span&gt;
&lt;span class="k"&gt;*&lt;/span&gt; When you see &lt;span class="s2"&gt;"Starting server at port 8080"&lt;/span&gt; displayed on the terminal, &lt;span class="nb"&gt;head &lt;/span&gt;over to your browser and search &lt;span class="s2"&gt;"localhost://8080/"&lt;/span&gt;&lt;span class="nb"&gt;.&lt;/span&gt;

&lt;span class="o"&gt;![&lt;/span&gt;Image description]&lt;span class="o"&gt;(&lt;/span&gt;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x83il13okhguxzbigvm6.png&lt;span class="o"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;*&lt;/span&gt; Open new tab on your browser and search&lt;span class="s2"&gt;"localhost:8080/form.html"&lt;/span&gt;&lt;span class="nb"&gt;.&lt;/span&gt;
&lt;span class="k"&gt;*&lt;/span&gt; A form as the one shown below will be displayed.

&lt;span class="o"&gt;![&lt;/span&gt;Image description]&lt;span class="o"&gt;(&lt;/span&gt;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bz0i9v7ox5zp1kk6jtdc.png&lt;span class="o"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;*&lt;/span&gt; Upon submitting the form after filling &lt;span class="k"&gt;in &lt;/span&gt;the name and address field, the following message is displayed.

&lt;span class="o"&gt;![&lt;/span&gt;Image description]&lt;span class="o"&gt;(&lt;/span&gt;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t22b2zv0ix944r5z57i2.png&lt;span class="o"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;*&lt;/span&gt; This shows that our web server is working as expected.

&lt;span class="c"&gt;## Resources&lt;/span&gt;
&lt;span class="k"&gt;*&lt;/span&gt; Find the GitHub repository on this &lt;span class="o"&gt;[](&lt;/span&gt;https://github.com/JosephOkumu/WebServer&lt;span class="o"&gt;)&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
      <category>go</category>
      <category>backenddevelopment</category>
      <category>programming</category>
      <category>webserver</category>
    </item>
    <item>
      <title>Building a URL Shortener in Go: A Step-by-Step Guide</title>
      <dc:creator>TekniksMila</dc:creator>
      <pubDate>Sun, 03 Mar 2024 21:06:56 +0000</pubDate>
      <link>https://dev.to/josephokumu/building-a-url-shortener-in-go-a-step-by-step-guide-3759</link>
      <guid>https://dev.to/josephokumu/building-a-url-shortener-in-go-a-step-by-step-guide-3759</guid>
      <description>&lt;p&gt;Introduction&lt;/p&gt;

&lt;p&gt;A server is a specialized system whose role is to respond to requests made by computers over a network. Servers are very critical since they provide hosting for websites and applications, and they also facilitate communication over a network. In this article, let's dive into creating a simple HTTP server that serves files and handles form submissions and requests to specific endpoints.&lt;br&gt;
Prerequisites&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Basic understanding of Go and web development concepts.

Must have Go installed. If you do not have Go installed, first navigate here https://go.dev/doc/manage-install to install Go.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Project directory structure&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Open terminal.

Create a directory with the name 'WebServer'.

Navigate into the 'WebServer' directory.

Initialize a new Go module.

Create a file with the name 'main.go'.

Create a new directory inside the 'WebServer' directory and name it 'files'.

Navigate into the files directory.

Create two files with the names index.html and form.html.

 mkdir WebServer
 cd WebServer
 go mod init example/WebServer
 touch main.go
 mkdir files
 cd files
 touch index.html
 touch form.html
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The code&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Open the index.html file and write the code as shown below. This will display a static web page.
&lt;/code&gt;&lt;/pre&gt;


&lt;br&gt;
          static website&lt;br&gt;&lt;br&gt;
      &lt;br&gt;
      &lt;br&gt;
          &lt;h2&gt;static website&lt;/h2&gt;
&lt;br&gt;
      &lt;br&gt;
  

&lt;p&gt;Open the form.html file and write the code as shown below: When rendered, this will display a form with name and address text fields.&lt;/p&gt;

&lt;p&gt;&amp;lt;!DOCTYPE html&amp;gt;&lt;br&gt;
  &lt;br&gt;
      &lt;/p&gt;
&lt;br&gt;
          &lt;br&gt;
      &lt;br&gt;
      &lt;br&gt;
          &lt;br&gt;
              &lt;br&gt;
              Name&lt;br&gt;
              Address
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;          &amp;lt;input type="submit" value="submit"/&amp;gt;
          &amp;lt;/form&amp;gt;
      &amp;lt;/div&amp;gt;
  &amp;lt;/body&amp;gt;
&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;Open main.go. Here we start off by declaring the main package, then import the packages that are necessary for the working of our program.&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  package main

  import (
      "fmt"
      "log"      // Importing the log package for logging
      "net/http" // Importing the net/http package for HTTP server functionality
  )

Next we create a function that handles form submissions.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;func formHandler(w http.ResponseWriter, r *http.Request) {&lt;br&gt;
    // ParseForm parses the raw query from the URL and updates r.Form&lt;br&gt;
    if err := r.ParseForm(); err != nil {&lt;br&gt;
        fmt.Fprintf(w, "ParseForm() err: %v", err)&lt;br&gt;
        return&lt;br&gt;
    }&lt;br&gt;
    fmt.Fprintf(w, "POST request successful")&lt;br&gt;
    name := r.FormValue("name")               // Retrieve the value of the 'name' parameter from the form&lt;br&gt;
    address := r.FormValue("address")         // Retrieve the value of the 'address' parameter from the form&lt;br&gt;
    fmt.Fprintf(w, "Name = %s\n", name)       // Print the name to the response writer&lt;br&gt;
    fmt.Fprintf(w, "Address = %s\n", address) // Print the address to the response writer&lt;br&gt;
}&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Create a function that handles requests to the /hello endpoint.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;func helloHandler(w http.ResponseWriter, r *http.Request) {&lt;br&gt;
    if r.URL.Path != "/hello" {&lt;br&gt;
        http.Error(w, "404 not found", http.StatusNotFound)&lt;br&gt;
        return&lt;br&gt;
    }&lt;br&gt;
    if r.Method != "GET" {&lt;br&gt;
        http.Error(w, "method is not supported", http.StatusNotFound)&lt;br&gt;
        return&lt;br&gt;
    }&lt;br&gt;
    fmt.Fprintf(w, "hello!") // Respond with "hello!" for GET requests to /hello endpoint&lt;br&gt;
}&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Create a main function that defines a simple HTTP server that serves static files from the ./files directory and handles requests to specific endpoints (/form and /hello) with custom handler functions.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;func main() {&lt;br&gt;
    fileServer := http.FileServer(http.Dir("./files"))&lt;br&gt;
    // Create a file server handler for serving static files from ./files directory&lt;br&gt;
    http.Handle("/", fileServer)            // Handle requests to root path with fileServer handler&lt;br&gt;
    http.HandleFunc("/form", formHandler)   // Handle requests to /form endpoint with formHandler function&lt;br&gt;
    http.HandleFunc("/hello", helloHandler) // Handle requests to /hello endpoint with helloHandler function&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fmt.Printf("Starting server at port 8080\n")

if err := http.ListenAndServe(":8080", nil); err != nil {
    log.Fatal(err) // Log any errors that occur during server startup and exit with error status
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;Executing the program&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Save the files you have created.

On the terminal type the following command:
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;go run main.go&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;When you see "Starting server at port 8080" displayed on the terminal, head over to your browser and search "localhost:8080".

Open new tab on your browser and search "localhost:8080/form.html".

A form as the one shown below will be displayed.

Upon submitting the form after filling in the name and address field, the following message is displayed.

This shows that our web server is working as expected.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Resources&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Find the code in my GitHub repository. Here is the link

https://github.com/JosephOkumu/WebServer
&lt;/code&gt;&lt;/pre&gt;

</description>
      <category>go</category>
      <category>backenddevelopment</category>
      <category>programming</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Building a URL Shortener in Go: A Step-by-Step Guide</title>
      <dc:creator>TekniksMila</dc:creator>
      <pubDate>Sat, 24 Feb 2024 23:02:28 +0000</pubDate>
      <link>https://dev.to/josephokumu/building-a-url-shortener-in-go-a-step-by-step-guide-1np8</link>
      <guid>https://dev.to/josephokumu/building-a-url-shortener-in-go-a-step-by-step-guide-1np8</guid>
      <description>&lt;h2&gt;
  
  
  Introduction:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;URL shortening is a technique used used to convert lengthy and complex URLs into shorter user-friendly versions. These shortened URLs are preferably advantageous compared to the original URLs, since they reduce visual complexity of the original URLs making them easier to read and remember thus promoting user engagement and click-through rates. Additionally, shortened URLs can be easily shared on spaces where available space is limited.&lt;/li&gt;
&lt;li&gt;In this article I am going to walk you through the process of building a URL shortener in Go.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Prerequisites:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Basic understanding of Go, HTTP servers and web development concepts.&lt;/li&gt;
&lt;li&gt;You must have Go installed in your computer system. If you do not have Go installed, first navigate to &lt;a href="https://go.dev/doc/manage-install"&gt;link&lt;/a&gt; to install Go.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Creating Project Directory and files:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Open terminal, create a project directory and name it "URL-Shortener".&lt;/li&gt;
&lt;li&gt;Navigate inside the "URL-Shortener" directory.&lt;/li&gt;
&lt;li&gt;Initialize a new Go module. &lt;/li&gt;
&lt;li&gt;Create a main.go file. Make sure the commands are entered line by line as shown below.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir URL-Shortener
cd URL-Shortener
git mod init url-shortener
code main.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Writing the Go code:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Open the main.go file. This is where you will write the code.&lt;/li&gt;
&lt;li&gt;Start off by declaring the main package. Import the necessary packages for running the program. "fmt" for formatting and printing, "math/rand" is for random number generation, "net/http" is for HTTP server functionality, "strings" is for string manipulation, and "time" for time-related functions.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main
import (
    "fmt"
    "math/rand"
    "net/http"
    "strings"
    "time"
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Create a global variable "ShortURLs" which is a map that will store the shortened URLs of type string as key, and their corresponding original URLs of type string as value.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ShortURLs is a map that stores shortened URLs with their corresponding original URLs.
var shortURLs = make(map[string]string)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;The main function sets up HTTP request handlers for different endpoints and starts the HTTP server on port 3030. The http.handleFunc() is used to map HTTP request paths to corresponding handler functions.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    // Set up HTTP request handlers
    http.HandleFunc("/", handleForm)           //Handle root endpoint
    http.HandleFunc("/shorten", handleShorten) // Handle URL shortening endpoint
    http.HandleFunc("/short/", handleRedirect) // Handle redirecting to original URL

    // Start HTTP server
    fmt.Println("URL Shortener running on: 3030")
    http.ListenAndServe(":3030", nil)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;The handleForm function is the handler function for GET requests to the root endpoint ("/"). It displays an HTML form for submitting a URL that needs to be shortened.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// handleForm handles GET requests to the root endpoint and displays the URL shortening form
func handleForm(w http.ResponseWriter, r *http.Request) {
    if r.Method == http.MethodPost {
        http.Redirect(w, r, "/shorten", http.StatusSeeOther)
        return
    }

    w.Header().Set("Content-type", "text/html")
    fmt.Fprint(w, `
        &amp;lt;!DOCTYPE html&amp;gt;
        &amp;lt;html&amp;gt;
        &amp;lt;head&amp;gt;
            &amp;lt;title&amp;gt; URL-Shortener&amp;lt;/title&amp;gt;
        &amp;lt;/head&amp;gt;
        &amp;lt;body&amp;gt;
            &amp;lt;h2&amp;gt;URL-Shortener&amp;lt;/h2&amp;gt;
            &amp;lt;form method= "post" action="/shorten"&amp;gt;
                &amp;lt;input type="url" name="url" placeholder="Enter a URL" required&amp;gt;
                &amp;lt;input type="submit" value="Shorten"&amp;gt;
            &amp;lt;/form&amp;gt; 
        &amp;lt;/body&amp;gt;
        &amp;lt;/html&amp;gt;
    `)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;The handleShorten function is the handler for POST requests to the "/shorten" endpoint. It generates a shortened URL, stores the URL and its original counterpart in a map and renders an HTML response that displays both URLs.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// handleShorten handles POST requests to the /shorten endpoint and generates a shortened URL
func handleShorten(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
        return
    }

    // Get the original URL from the form
    originalURL := r.FormValue("url")
    if originalURL == "" {
        http.Error(w, "URL parameter is missing", http.StatusBadRequest)
        return
    }

    // Generate a short key and store the original URL
    shortKey := generateShortKey()
    shortURLs[shortKey] = originalURL

    // Construct the shortened URL
    shortenedURL := fmt.Sprintf("http://localhost:3030/short/%s", shortKey)

    // Render HTML response with original and shortened URLs
    w.Header().Set("Content-Type", "text/html")
    fmt.Fprint(w, `
        &amp;lt;!DOCTYPE html&amp;gt;
        &amp;lt;html&amp;gt;
        &amp;lt;head&amp;gt;
            &amp;lt;title&amp;gt; URL-Shortener&amp;lt;/title&amp;gt;
        &amp;lt;/head&amp;gt;
        &amp;lt;body&amp;gt;
            &amp;lt;h2&amp;gt;URL-Shortener&amp;lt;/h2&amp;gt;
            &amp;lt;p&amp;gt;Original URL: `, originalURL, `&amp;lt;/p&amp;gt;
            &amp;lt;p&amp;gt;Shortened URL: &amp;lt;a href="`, shortenedURL, `"&amp;gt;`, shortenedURL, `&amp;lt;/a&amp;gt;&amp;lt;/p&amp;gt;
        &amp;lt;/body&amp;gt;
        &amp;lt;/html&amp;gt;
        `)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;handleRedirect handles requests to shortened URLS ("/short"). It extracts the short key from the request path, looks up the original URL, and redirects the client to the original URL.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// handleRedirect handles requests to shortened URLs and redirects to the original URL.
func handleRedirect(w http.ResponseWriter, r *http.Request) {
    // Extract the short key from the request path
    shortKey := strings.TrimPrefix(r.URL.Path, "/short/")
    if shortKey == "" {
        http.Error(w, "Shortened key is missing", http.StatusBadRequest)
        return
    }

    // Retrieve the original URL from the map
    originalURL, found := shortURLs[shortKey]
    if !found {
        http.Error(w, "Shortened key not found", http.StatusNotFound)
        return
    }

    // Redirect to the orginal URL
    http.Redirect(w, r, originalURL, http.StatusMovedPermanently)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;The generateShortKey function is responsible for generating a short random key for URL shortening. It uses a predefined character set and a key length of 6 characters to create the short key.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// generateShortKey generates a short random key for URL shortening
func generateShortKey() string {
    const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    const keyLength = 6

    rand.Seed(time.Now().UnixNano())
    shortKey := make([]byte, keyLength)
    for i := range shortKey {
        shortKey[i] = charset[rand.Intn(len(charset))]
    }
    return string(shortKey)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Executing the URL Shortener Program
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Save the main.go file.&lt;/li&gt;
&lt;li&gt;Run the program by typing on the terminal the command below:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go run main.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;It will display that the URL Shortener is running on port 3030.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;URL Shortener running on: 3030
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Open your browser and on the address bar type &lt;a href="http://localhost:3030"&gt;http://localhost:3030&lt;/a&gt; then search.&lt;/li&gt;
&lt;li&gt;Once the new page loads, enter the URL you want to shorten in the text field, and click the "shorten" button.&lt;/li&gt;
&lt;li&gt;Find the shortened URL displayed on the screen.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Resources.
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;You can find the whole working code on my Github profile. Here is the &lt;a href="https://github.com/JosephOkumu/URL-Shortener"&gt;link&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Also find a short video demonstration showing the end result on Twitter. Here is the &lt;a href="https://twitter.com/jaykush_0/status/1761349560041869736"&gt;link&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    <item>
      <title>Surviving the Zone01 Software Development Piscine Bootcamp in Kenya</title>
      <dc:creator>TekniksMila</dc:creator>
      <pubDate>Sat, 23 Dec 2023 12:53:36 +0000</pubDate>
      <link>https://dev.to/josephokumu/surviving-the-zone01-software-development-piscine-bootcamp-in-kenya-492p</link>
      <guid>https://dev.to/josephokumu/surviving-the-zone01-software-development-piscine-bootcamp-in-kenya-492p</guid>
      <description>&lt;p&gt;Embarking on the Zone01 Piscine felt like diving into uncharted waters, a digital sea of challenges that promised to test the spirit of aspiring coders. The preliminary online test marked my initiation, a gateway to the grandeur of the piscine experience. Invitations were extended and I eagerly embraced the opportunity to dive into the first-ever Zone01 piscine in East Africa, a journey that would define my coding prowess.&lt;/p&gt;

&lt;p&gt;Before diving into the coding abyss, a prelude unfolded, a check-in session where details of the program were revealed unto us. The piscine, a French term which refers to a swimming pool and is also associated with 42 school, involves immersing candidates to the deep end of the pool. The analogy struck hard, novice swimmers get thrust into the deep end and their survival is dependent on mastering the art of coding.&lt;/p&gt;

&lt;p&gt;The dawning day of the piscine unleashed a torrent of challenges. A hundred pisciners were cast into the coding sea. Each day timed coding exercises synonymous to turbulent tides demanded resilience. The exercises tricky and daunting, required days of commitment, a marathon where completion was a victory unto itself.&lt;/p&gt;

&lt;p&gt;Sundays brought forth checkpoints which involved four hours of scrutiny to test the evolving coding prowess of the candidates. Immediately after the checkpoints collaborative coding tasks akin to synchronized swimming followed, a team effort in the turbulent waters of coding complexity. As the weeks passed by, the waves became relentless and unforgiving. By end of week two the piscine’s intensity weeded out the wavering leaving behind seventy-something of us who were resilient and undeterred, clinging to the hope of reaching the piscine’s shore.&lt;/p&gt;

&lt;p&gt;The climax of the piscine came in the form of a final checkpoint, an eight-hour marathon with 11 coding questions. I managed to tackle up to question six in the checkpoint and like a swimmer momentarily overwhelmed by the depths, I faced a formidable question seven that left me gasping for breath. The piscine concluded, we exchanged farewells and dispersed awaiting the verdict that lingered on the horizon.&lt;/p&gt;

&lt;p&gt;Anticipation gripped us for two weeks, and then like a beacon on a stormy night, the email arrived. Success! The journey through the piscine’s depths had yielded triumph. Out of a hundred, only 28 were selected for the program, and I was among them. The dream of being a full stack developer is in the offing, courtesy of the Zone01 program.&lt;/p&gt;

&lt;p&gt;To those daring to plunge into the piscine’s waters, remain cognizant of these insightful tips: Embrace the intensity; perseverance is your anchor. Learn ceaselessly for knowledge is the compass steering you through the coding currents. Do not compare or compete with others, be true to yourself. Sacrifice sleep for the sake of code; there are no shortcuts in the piscine. Last but not least, character matters. Honesty and integrity will help you navigate the currents of the selection. To future pisciners, may the code be ever in your favor.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>coding</category>
      <category>go</category>
      <category>piscine</category>
    </item>
  </channel>
</rss>
