Go (also known as Golang or Go language) is an open-source programming language mostly used to develop tools, command line interfaces, and websites. It relies on simplicity, dependability, and efficiency at its foundation to overcome the faults of its ancestors. Go is not the latest trend in programming language theory, or a buzz-word. Trust me it is a strong language to solve real-world program or so I hope.
golang unicorn by clgtart sticker shop
Go features garbage collection, a package system, first-class functions, lexical scope, and immutable UTF-8-based strings. It is quick to compile and execute, and its concurrency architecture is simple to comprehend. Additionally, Go features a robust standard library and a large, welcoming community.
This post is an hands-on introduction to Go using annotated example program. Learn by doing is the fast way to learn or so I hope.
here is basic hello world look like
package main
import "fmt"
func main() {
fmt.Println("hello world")
}
In this example program, we will build a simple tool that extract URL from a csv file. We could do it with just regular expression alone, however this is not a post about super effective, but as a learning steps.
So basically we will do:
Golang os.Stat() is a built-in function used to get the file status for a given file or directory. We can use it check if a file exists or not.
func exists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
We do not want to read the entire file into memory because it is a poor practice; reading the file line by line is far more effective and memory efficient.
file, err := os.Open("/path/to/file.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
Let's step through this.
First we use os.Open
to open the file, and defer
to close it. defer
is used to ensure that a function call is performed later in a program’s execution, usually for purposes of cleanup. In our case it will close our file, ensure no memory leak.
Then later we use bufio.NewScanner
to read the file line by line, print each like to stdin for make sure it work. (my habit)
Instead of printing each line of the file to stdin, our basic software will break the line into an array. Lines in csv are frequently separated by commas, so here we go.
for scanner.Scan() {
line := scanner.Text()
for _, s := range strings.Split(line, ",") {
// doing with s
}
}
We wanted to locate a URL, therefore we assumed that any text that begins with "http" is a URL.
if strings.HasPrefix(s, "http") {
// extract s
}
package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
var filepath = "/path/to/file.txt"
func exists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
func main() {
result := []string{}
if !exists(filepath) {
log.Fatal("file not found!")
}
file, err := os.Open(filepath)
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
for _, s := range strings.Split(line, ",") {
if strings.HasPrefix(s, "http") {
// extract s
result = append(result, s)
}
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
// here is our extracted URL
fmt.Println(result)
}
If you’ve made it to the end, congratulations! Hopefully, you had a lot of fun along the way. If you’d like to see more, check out the official Go website. There, you can follow the instruction, play interactively, and read a lot. Aside from a tour, the documentation concise overview of the language.
The source code for the standard library is must read for any Go developer. I learn a lot if it. It showcases the best of readable and understandable Go, Go style, and Go idioms. It is thoroughly documented and Alternatively, you can view the source code by clicking on a function name in the documentation!
Also check out Go by Example is another excellent resource for learning Go.
Codeacademy provides a free Learn Go course, which is worth a look.
If you like golang, here is some others articles of the same author (me) about golang topic. Check it out !
Hi there. Nodeepshit is a hobby website built to provide free information. There are no chargers to use the website.
If you enjoy our tutorials and examples, please consider supporting us with a cup of beer, we'll use the funds to create additional excellent tutorials.
If you don't want or unable to make a small donation please don't worry - carry on reading and enjoying the website as we explore more tutorials. Have a wonderful day!