Back to Projects

Contacts Book

What?

Let’s follow this tutorial to understand some basic concepts of Golang while creating a command line application to organize our contacts. But first we need to define what features or functions should cover a basic contact managment application.

What fields have a contact?

A contact must store basic personal data to reach somebody; for example: name, phone number and address. This will be our basic contact data. When we refer to a set of data that represents something like a contact for example we call it the Model. So, using that naming convention, our contact data model is:

# Contact
- Name: string
- PhoneNumber: string
- Address: string

What features should we develop?

To make this tool useful, we need to allow the user to Create, Read, Update and Delete a Contact or a CRUD. Also we need to be able to seach a contact. All these features should be accesible from the command line.

Tasks

  • Create a contact
  • Read a contact
  • Update a contact
  • Delete a contact
  • Seach a contact
  • Access all the features with a menu

How?

First we need to capture the contact data form the terminal

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	CreateContact()
}

func CreateContact() {
	// Create a buffer for reading form the standard input
	reader := bufio.NewReader(os.Stdin)

	// Ask for contact name
	fmt.Print("Enter contact name: ")
	name, _ := reader.ReadString('\n')

	// Ask for contact phone
	fmt.Print("Enter contact phone: ")
	phone, _ := reader.ReadString('\n')

	// Ask for contact address
	fmt.Print("Enter contact address: ")
	address, _ := reader.ReadString('\n')

	fmt.Println("==== Contact summary ====")
	fmt.Println("Name:", name)
	fmt.Println("Phone:", phone)
	fmt.Println("Address:", address)
}

As you can see we call reader.ReadString everytime we want to capture data from the command line or standard input. This method reads from the stdin and fills a buffer until the key Enter or \n once it reads Enter the buffer is moved to a variable.

Back to Projects