Categories
Golang regex

Golang Programming Language. Reading files to get deeper.

I am going to drop a snippet to introduce some cool concepts about the Golang Programming Language that may help you to see its coolness and maybe adopt it by yourself.

I am going to use regex, buffered IO, defered close, and handle errors for all of this in less than 60 lines with comments.

Comments may guide you, but any question can be answered to me about this code. Duckduckgo may also help you if you are not into doing that social thing.

package main

// Not say the import syntax is not cool.
import (
        "bufio"
        "fmt"
        "os"
        "regexp"
)

func main() {
        // The path to the file.
        path := "hola"
        // Opening the file.
        buffer, err := os.Open(path)
        // Error handling.
        if err != nil {
                dief("Unable to open file %s: %s", path, err.Error())
        }
        // We make this function execute on function return, expected or unexpected.
        defer func() {
                // Closing the buffer.
                err = buffer.Close()
                if err != nil {
                        dief("Unable to close buffer: %s", err.Error())
                }
        }()
        // Regexes are a useful tool to introduce.
        re, err := regexp.Compile("hola.")
        if err != nil {
                dief("Regexp failed to compile, malformed regex: %s", err.Error())
        }

        scanner := bufio.NewScanner(buffer)
        line_number := 1
        // Conditional for loop, works like while in other languages.
        for scanner.Scan() {
                this_line := scanner.Text()
                // In multiline arguments , is required also for the last argument.
                // The compiler expects , or ) not newline. :)
                fmt.Printf(
                        "Found hola %d times in line %d of %s\n",
                        len(re.FindAllString(this_line, -1)),
                        line_number,
                        path,
                )
        }
}

// Variadic arguments to a die helper function.
func dief(format_string string, args ...interface{}) {
        // We can pass variadic arguments to other functions which is pretty useful sometimes.
        fmt.Fprintf(os.Stderr, format_string+"\n", args...)
        os.Exit(1)
}

Here is some example content for the hola file we are reading.

holae huteoauhshthola hola ete hola
hola 
hola
holatttthola

And its example output, may differ since I left trailing whitespace sometimes in the file on purpose, but clipboard and WordPress may have omited it.

Found hola 3 times in line 1 of hola
Found hola 1 times in line 1 of hola
Found hola 0 times in line 1 of hola
Found hola 1 times in line 1 of hola
Categories
Golang

The Golang Programming Language. Introduction.

Since a few months I have been pretty hyped by the Golang Programming language since it provides much of the advantages in fast development of interpreted languages, say PHP, Javascript or Perl like tons of libraries for every job and advantages typical from a compiled language like a powerful type system and being blazing fast.

But how does the code in Golang look? This is what this blog post is about.

The first program we will like do is of course a simple hello world let’s do it:

mkdir helloworld
cd helloworld
go mod init helloworld

That will generate a go.mod file suitable for our needs, now we are going to code the hello world program into the file main.go in the folder we just did cd into:

package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello world")
}

Now that we have the code and the go.mod file compiling will give us a executable with the name we passed into go mod init, let’s try it.

go build && ./helloworld

Hello world should have been printed into your terminal.

Congratulations, you just made your first program in Go, now let’s try moving it into a web.

Golang gives us bundled into the language the net/http library which allows web development in a way very similar to the Perl’s Mojolicious.

This code will spin a web server listening into the port 8080 which prints hello world when visited.

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", helloWorldHandler)
    http.ListenAndServe(":8080", nil)
}

func helloWorldHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello world")
}

As you may figured out Golang is a very powerful language for web development, not only routing is easy thanks to net/http, but also features tons of useful libraries you may use to extend your program.

I recommend if you are interested on further expand your knowledge of this language take a look at https://golang.org/doc/tutorial/ and of course write some code using this language to test its capabilities.