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.

By sergiotarxz

I am a software developer with high interest on free software.

Leave a Reply

Your email address will not be published. Required fields are marked *