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.

package main
import (
"fmt"
"regexp"
)
func printMatches (r *regexp.Regexp, s string ) {
// Use the FindAllString() function to find all
// the resulting matching strings.
// FindAllString() will return nil if it doesn't
// find any matches.
// If it does it will return a slice containing
// all the matches
matches := r.FindAllString(s,-1)
if matches != nil {
// If matches were found, traverse the slice
// and print them one by one
fmt.Println("Here are the matches found in ", s)
for _, match := range matches {
fmt.Println(match)
}
} else {
// If no matches found, output an error message
// and return
fmt.Println("No Alpha Numeric Words found in", s)
}
}
func main() {
// Compile a regular expression that matches
// alpahnumeric words. We get a regular expression
// object in return.
alphaNumericWords := regexp.MustCompile(`\w+`)
// Pass the test string and the object to our function
// that checks if regular expression matches or not.
// and print the results
input1 := "You gotta be kidding me, Mr 23"
printMatches(alphaNumericWords,input1);
input2 := "...... !!!!!"
printMatches(alphaNumericWords,input2);
}
view raw RegExp1.go hosted with ❤ by GitHub



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.