Computing

Create a Todo App in Golang with Basic HTML, JavaScript, and CSS

In this tutorial, let’s do something enjoyable. In this blog, we’ll discuss creating a todo app using Golang. Today, iOS app development and Android app development is a real possibility as Golang has all the required features. Additionally, we’ll use fundamental HTML, CSS, and JavaScript for the frontend style.

So without further ado, let’s start.

Preliminary Task 

A new directory has to be made first. Because I’m using Windows, I’ll use the Command Prompt. However, if you’re using Linux or macOS, you have to utilize Terminal. Since, I store all my projects in go-workspace, I’ll type:

cd go-workspace 

mkdir list 

cd list

code .

The VS Code opens after the final code (my choice of text editor). You can use Goland, Vim, and other IDEs as you see fit.

Begin with Coding in the VS Code

In the directory “list,” in the Go source file titled “main.go,” we will now put the following code into Visual Studio Code.

package main

import (

“html/template”

“log”

“net/http”

)

var tmpl *template.Template

type Task struct {

Item string

Close bool

}

type Notes struct {

Title string

Todos []Task

}

  • Let’s try to understand the code now. The code will have several functions where we’ll employ templates, in addition to other locations. This is necessary since we must access the template.
  • To enable this, we’ll need to create a global variable with the name var tmpl *template.Template. When we call this tmpl, we are establishing a reference and a template object. As you may have guessed, importing the net/http package is essential.
  • The two structs are Task and Notes. The Task consist of two data fields, the Item of type string and Close of type boolean. The Notes consists of Title string and an array Todos []Task 

func list(w http.ResponseWriter, r *http.Request) {

data := Notes {

Title: “ToDo List”,

Todos: []Taskt{

{Item: “Take notes”, Close: true},

{Item: “Revise notes”, Close: false},

{Item: “Take test”, Close: false},

},

}

tmpl.Execute(w, data)

}

  • You can see that we then created a list function. Additionally provided are the parameters w http.ResponseWriter and r *http.Request. It is obvious that a reference to the request object and a response writer are being utilised. The ResponseWriter interface is an important part in producing an HTTP response. The Request method makes reference to the HTTP methods like GET, POST, etc.
  • After that, an object is formed and its data is supplied with the Notes values. We are doing an inline instantiation of the Notes. The title “To Do List” is thus required.
  • The next step is to arrange the Todos into an array. Each array will make a reference to a basic struct in this case. We encapsulate the function in tmpl.Execute (w, data), which effectively takes the template objects. The only things being transmitted are the ResponseWriter and the data.

func main() {

mux := http.NewServeMux()

tmpl = template.Must(template.ParseFiles(“templates/sign.gohtml”))

fs := http.FileServer(http.Dir(“./static”))

mux.Handle(“/static/”, http.StripPrefix(“/static/”, fs))

mux.HandleFunc(“/list”, list)

log.Fatal(http.ListenAndServe(“:8080”, mux))

}

  • Let’s examine this section of code. Starting with a simple setup is the first step. Here, mux:= http.NewServeMux is being constructed as a mux server. Allocating and returning a new ServeMux is done by the NewServeMux.
  • The ServeMux is a multiplexer for HTTP requests. It launches the handler after comparing each incoming request’s URL against a register of patterns.
  • We are creating an endpoint for the URL that will be “/list” and have the method list since we have constructed a function with the name list.
  • The statement tmpl = template.Must(template.ParseFiles(“templates/sign.gohtml”)), instantiates tmpl. The template.Must is necessary for wrapping around the templates. If it’s absent, the application will break since it can’t get the required templates. The following code, template.ParseFiles, represents the string of templates.
  • To run the server, we type log.Fatal(http.ListenAndServe(“:8080”, mux)).
  • Now, let us understand the following two statements. 

fs := http.FileServer(http.Dir(“./static”))

mux.Handle(“/static/”, http.StripPrefix(“/static/”, fs))

In these two instructions, we use the http directory “./static/” to create a file server using fs.Next. After dealing with the “static,” we must then Strip the “/static/” Prefix.

If you are working on a macOS system, then the Golang iOS app development process will be the same. So, you should follow the process properly and implement the steps. 

Moving on to the Sign.gohtml File 

Next, we will build  ‘templates’ folder inside the ‘list’ directory. Following this, we will create a source file named sign.gohtml inside ‘templates’ folder and we type:

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta http-equiv=”X-UA-Compatible” content=”IE=edge”>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <link rel=”stylesheet” href=”/static/css/outline.css”>

    <title>TODO</title>

</head>

<body>

    <h1>{{ .Title }}</h1>

    <ul>

        {{ range .Todos }}

            {{ if .Close }}

                <li class=”end”>{{.Item}}</li>

            {{ else }}

                <li>{{.Item}}</li>

            {{ end }}

        {{ end }}

    </ul>

    <script src=”/static/js/text.js” type=”text/javascript”></script>

</body>

</html>

Shift Your Focus to the Static Folder 

The static folder, which is located in the directory “list,” is the next stop. The css and js folders are contained in this folder. The js folder consists of text.js and the css folder consists of outline.css file. 

Getting Started in text.js File 

We type:

let items = document.getElementsByTagName(“li”)

for (let i=0; i<items.length; i++) {

 items[i].addEventListener(“click”, () => {

        items[i].classList.toggle(“finish”)

    })

}

Typing the Code in the outline.css File 

We type:

body {

    background-color: orange;

    color: steelblue;

    width: 50%;

    margin: 0 auto;

}

ul li {

    cursor: pointer;

}

.close {

    text-decoration: line-through;

}

Lastly, Run the Program 

Now that everything has been done, we will have to run the program. For this, we will type go run main.go. Then we open the browser and run the application on the 8080 portal. We get:

As you can see, the program is successful. So, try it on your own and see the result for yourself. 

Related Articles

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to top button