golang web app

The steps to build a simple web app with Golang will be different for each app. However, the underlying logic will be similar except for the complexity of each web application. Web development in Golang is super fun as the language is extremely fast and it helps in creating a secure application. 

Initial Tasks 

Before we get started with the application development, there are certain things that we have to do. We have to create a new directory wappdev in the go workspace. To accomplish this, we have to resort to Command Prompt on Windows. And we have to type the code:

cd go-workspace 

mkdir wappdev

cd wappdev

code .

  • As we put down the statement code ., the VS Code (my choice of IDE) gets launched. 
  • We get to see that the wappdev directory has been created on the VS Code. Following this, we create a folder called “structure” and a file called “structure.html” within it.
  • Next, we build a brand-new subdirectory named stable within the wappdev directory. Two other files are also included: structure.css and sale.png (which contain a random image).
  • At last, we create a file named main.go, where we will write down the main logic. 

Let’s Start with main.go File 

  • We type the following code:

package main

import (

“fmt”

“html/template”

“net/http”

“time”

)

  • There is nothing to explain in this section. We have imported four different packages: html/template, fmt, net/http and time. 

type Greetings struct {

Sale string

Time string

}

  • As you can see, we have created a struct Greetings that contains two data fields Sale and Tie of type string. We move onto function main(). 

func main() {

hi := Greetings{“Sale Starts Now”, time.Now().Format(time.Stamp)}

template := template.Must(template.ParseFiles(“structure/structure.html”))

http.Handle(“/static/”, http.StripPrefix(“/static/”, http.FileServer(http.Dir(“static”))))

http.HandleFunc(“/”, func(w http.ResponseWriter, r *http.Request) {

if sale := r.FormValue(“sale”); sale != “” {

hi.Sale = sale

}

if err := template.ExecuteTemplate(w, “structure.html”, hi); err != nil {

http.Error(w, err.Error(), http.StatusInternalServerError)

}

})

fmt.Println(http.ListenAndServe(“:8000”, nil))

}

  • Now let’s delve deep into the program. We have created a variable hi, we have initialized the values of the data fields. The Sale string has the string “Sale Starts Now”. The time.Now() function is crucial as it displays the current time as per the format Format(time.Stamp). 
  • We also construct a template variable. You must be aware that the Must function is part of the template package in this case. This is used to verify the template’s authenticity. 
  • The purpose of a template.Parsefiles() may now be a question on your mind. It is responsible for creating a brand-new template. The structure/structure.html file’s several template definitions are subsequently processed.
  • We are able to create http.Handle as we have imported the package net/http. The handle accepts the http.Handler. Use the http.StripPrefix to access the static files housed in the ‘stable’ subdirectory within the ‘weappdev’ directory. Because we supplied it as a parameter, it transfers the request’s processing to “stable.”
  • The handler provided by FileServer processes HTTP requests using the root-level information of the file system. You are converting the string “stable” into a http.Dir type.
  • What does the method HandleFunc achieve? Simply said, it provides a way to highlight the appropriate method for responding to requests for a specific route. The function (w http.ResponseWriter, r*http.Request) is very commonly used while creating APIs or web apps. It is used for reading and writing.
  • If the sale variable interprets the FormValue as “sale” and sale is not nil, the struct data field hi.Sale will now take the value “sale”.
  • The next step is to understand ExecuteTemplate’s function. The template application ends if there is a mistake. It is considering the template’s summary from structure.html (which we will check out later in the program).
  • The http package utilizes http.StatusInternalServerError to determine the status of any faults because it is responsible for providing client and server implementations.
  • While keeping an eye on the TCP network address to handle requests from incoming connections, ListenandServe first calls Serve with Handler.

Hopefully, you were able to understand the details of the program in this section. Web development in Golang is an important aspect and if you actually pay attention to the process, then you will be able to undertake difficult projects. 

Let’s Go to the HTML File 

In this section, we will type the code in the HTML file. 

<html>

   <head> 

         <meta charset=”UTF-8″>

         <link rel=”stylesheet” href=”/stable/structure.css”>

         <title>Welcome {{.Sale}}</title>

   </head>

   <body>

      <div class=”Greetings Centre”>Last day {{.Sale}}, {{.Time}}</div>

   </body>

</html>

  • The above-mentioned code is easy to comprehend. We are only outlining the structure or layout of the web page. The charset attribute helps draw attention to the character encoding that the HTML page specifies. The HTML5 specification also mandates that programmers use the UTF-8 character set.
  • The line <link rel=”stylesheet” is important to understand. It is letting us know that the external source (structure.css) is connected to the HTML content (structure.html). The “stylesheet” will control the document that appears on screen. 
  • In actual use, the HTML components should be divided into several classes. We employ <div class= “Hello Centre”> to divide the classes. The Last Day, Time, and value of Sale will all be shown.

With this, the HTML document comes to an end. 

Let’s Code in the CSS File 

Now, we will type the code in the structure.css file, which can be found inside the ‘stable’ folder. We type:

body {

    min-height: 150%;

    background-image: url(“/stable/sale.png”);

    background-blend-mode:  overlay;

    background-size: cover;

}

.hello {

    font-family: ‘Segoe UI’, Tahoma, Geneva, Verdana, sans-serif;

    font-size: 2rem;

    color:lightpink;

}

.center {

    height: 100vh;

     display: flex;

     justify-content: center;

     align-items: center

}

  • Basically, we have highlighted how the web page should look like. For body, we are highlighting the background image, background-blend-move, minimum height, and background-size. 
  • For .welcome, we highlight the font-size, font-family and color. 
  • For .center, we are using height of 100vh, display: flex, justify-content: center and align-items: center

As soon as we complete the program, we run it. How? Just type go run main.go in the terminal. And when you type localhost:8000 on the browser, you get:

Was it too complicated to understand the program? No, right? Hopefully, you will be able to handle even more complex projects in the upcoming future. All the best!

By Anurag Rathod

Anurag Rathod is an Editor of Appclonescript.com, who is passionate for app-based startup solutions and on-demand business ideas. He believes in spreading tech trends. He is an avid reader and loves thinking out of the box to promote new technologies.