Friday, March 29, 2019

Using Regular Expressions in Go

Go language provides package regexp for making use of regular expressions in Go programming. The syntax of the regular expressions is almost identical to that supported by other languages like Perl, Python etc.

Let's start with the basics. We will try to use regexp package to find out if a given text contains any alphanumeric words. By alphanumeric words, we mean any word that is comprised of letters or numerals.

To do this, we will compile a regexp object out of a regular expression. Then we use this regexp object on input strings to check if they contain any alphanumeric words or not, and if they do, we print each one of them.

Here is a program for doing this.




Tuesday, March 5, 2019

Writing the simplest HTTP server in Go

To write a very simple, HTTP server in Go, that serves just a single static page, you just need to do the following.

  • Import the net/http package
  • start listening on a port of your choice using http's ListenAndServe
  • server requests using a HTTP ResponseWriter.

Here is the code for this:-
package main
import (
"net/http"
"log"
)

func viewHandler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello there..."))
}

func main() {
    http.HandleFunc("/", viewHandler)
    log.Fatal(http.ListenAndServe(":8087",nil))
}
Using http.HandleFunc we choose to handle incoming requests on '/' path using the viewHandler function. After this, we start a ListenAndServe() function to start handling incoming HTTP requests on 8087.

Go ahead and build this and then run the exe. Your server has started. Now, open the browser and goto http://localhost:8087/

You should see a 'hello there...'.

Go has a pretty powerful HTTP library that allows you to do a lot of things. We shall explore more in the future.