Happy Coding

In Part I, we just converted a sequential program to a multithreaded one and did it with a very simple example. But real world problems are more complex then that. Now assume a server which confirms your login via OTP SMS and same is done for 10000 users per second. Now that’s what I called a problem.

Solution: As a simple design I will create independent jobs, one will handle the login part and other will handle the OTP SMS part. So, SMS job will just run independently of the login job. That’s how SMS job can be reused for other user logins. Now there is a need that both jobs must communicate.

Golang has provided a mechanism known as Channels. I this part of blog I will explain basics of channels.

Channels

In simple words, Channels are the connection between goroutines. Let’s discuss some facts and then a straight forward example will make it clear.

Each golang channel has a data type, like int, string or struct {}. E.g. ca chan int. ca is channel variable and chan int is how we can declare channel.

We need to use make() to actually create a channel. e.g. ch := make(chan int). If, we don’t make a channel it cannot be used and will cause panic.

We can pass channels as function arguments and they are automatically passed a s reference.

Using A Channel

Channel has three operations defined.

Read. (Eg. ch-<x) // write x to channel ch

Write. (x := <-ch) // read channel into x

Close. (We will discuss close in detail.)

Close

If we send on a channel after closing it, panic will occur.

If we read from a channel after closing it, first all the unread valued will be read and after that read will always read the zero value of channel.

Kinds of Channel

Unbuffered.

Buffered.

In this part we must stick to unbuffered channel and it’s complexities. In next blog we will take on buffered channel.

Unbuffered channels

Unbuffered channels are also called, Synchronous channels. Because they work in a manner that only one operation can be performed at a time, either Read or Write.

e.g.

ch := make(chan int) is a Unbuffered channel. There are few rules about them.

If channel is not empty, send operation will block. Executing a receive will make channel available for send.

If a channel is empty, receive operation will block. We have to perform send operation.

Size

A Goroutine starts life with a small stack, typically 2 KB. Because some go routines are too small for a 2 MB stack and stack of Goroutine is growable.

The size limit for a Goroutine stack may be as much as 1GB, so thread is limited for recursive operation because recursive stack greater then 2 MB will cause, stack overflow. Go o the other hand can grow it’s stack to 1 GB, WOW, now huge recursion is possible in Go.

Concurrent programming knowledge a necessity these days. Servers need to handle multiple connections and process them simultaniously. Mobile apps are working in a manner that, foreground and backgroung processing is done in saperate context. Since processors are growing in numbers not in speed, we need to design out programs in such a manner.

Goroutines

Goroutines are not threads, but they are like threads. Each concurrently executing activity is called Goroutine. As an example assume a problem in which we are processing multiple types of data and writing in multiple files. So, there are two ways to do that.

Sequential programming.

Concurrent programming.

I will just create an example, and will show you it’s really easy to convert a sequential program to concurrent program in go.

Problem:

Given a number of dollars, , and a list of dollar values for distinct coins, , find and print the number of different ways you can make change for dollars if each coin is available in an infinite quantity.

Assume you have unlimited change of { 2, 3, 5, 6}, now you have to tell in how many ways you can make a 10$.

There are many possible ways like, {2,2,2,2,2,} , {2,3,5}.

But how to determine the solution of problem?

There is a recursive solution, in which try all the combinations and if right one is found, increment the count. But doing it recursively is a complex task and the complexity will be O(power(n,m)) and the code is:

The solution is fine and clears few of the test cases, but it gets timeout for the large dataset. The basic problem is while designing our solution we are solving the problems again and again. Like, {6,4} is 10 and {6,2,2}is 10 and {2,2} is 4 and we are recalulating it again and again.

After a basic explanation of Abstract Pattern in Golang. There is need that, I should explain a more powerful design pattern, which will help in creating more complex objects. The pattern is Builder Pattern.

What is Builder Design Pattern

Design pattern books are boring. You may disagree but it’s my personal feeling. hehehe… But I will try make this part a bit interesting. Every book has example of same food company, even websites explaining design pattern are using same examples again and again.

But I will first user some theoretical terms and then with help of diagrams, I will explain it. Builder pattern comes in to picture when you have complex product. Means a product with may inputs, for e.g. A Car company like Audi, manufactures many kind of cars, although they all are cars but all are different, Audi Q3 , Audo Q4, Audi R8. How they accomplish it in a same factory is an example of Builder Pattern.

In builder pattern we just need to remember five components:

Director: Director performs all the required steps given inside builder to create a product. In our case our production line in our director. It will invoke all the abstract builder steps to create our Audi.

Hello friends, after Cryptography Part I back with my first example of crypto. Golang has a package AES. In the further blog, I will write a Client Server application, which runs on the encrypted data. So, ready to share some secret over network. Shhh…..

Hello friends, my job profile deals a lot with security. From last one year I have been working with Microsoft Crypto Providers, Openssl engines and lot’s of stuff. So, I started discovering the same in Golang. So, in this article I will explain the Golang crypto module with examples, and some use cases. Let’s start.

What is Cryptography

I simple terms, cryptography is a digital technology that secures your data, like passwords, credit card number or anything which you want to secure. It fulfills following four goals.

The four points are linked to Wikipedia pages. To go in details, you can refer same, I will explain them in very short definitions.

Confidentiality is data cannot be read by any other parties.

Data Integrity is , the crypt operation must not change data.

Authentication is, data must be read by Authenticated party.

Non-repudiation, is the party which is sending the data cannot deny, that they have not sent it.

Some Technical Terms

Cryptography Algorithms

Cryptography algorithms are algorithms which are needed when we do crypt operations, like encryption, decryption, sign and verify. In layman terms, we are locking our data. So, for locking our data we need a key and to unlock it we need the key. So all the cryptography is based on key.

Based on keys, cryptography can be classified in two categories:

Symmetric

Asymmetric

Symmetric Cryptography

Only one key can encrypt.

Same key can decrypt.

Both the parties need to hold key.

Asymmetric Cryptography

Consists of two keys, PUBLIC and PRIVATE

Data encrypted by Private can only be decrypted by Public.

data encrypted by Public can only be decrypted by Private.

This was a small description of crypto, now in next parts. I will do a client server example for both.

Crypto in Golang

Golang has a package, Golang Crypto. Which fulfills almost all the application crypto needs.

Hello programmers, how are you guys. A friend asked me for a crash course on Golang. So, I am making it really short. This post will be helpful for programmers who are new to Go and don’t know where to go in Golang. I will write a basic tutorial with links, so be ready for a fast pace tutorial or a simple crash course.

I will cover the following topics:

What is Go (little-little)

How to install and configure.

Run first go program.

Go types and variables and scope

Arrays , Slices and Maps

If-else and switch

Loops

Functions and Closures

Structure and Interfaces

What is Go

I will say it’s another programming language. I learned it because, being C++ programmer I was in need of a language which is same as C or C++ in terms of performance and helps me to code my small services which runs on network and devlopment is really fast paced . So, I start reading about Go and fell in love with the language. If you need some boogie details of go history visit, gaolang.org, it says, “Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.”

How to install and configure

Go to Golang Websiteand just download it, on windows it is installed in C:\Go and On Mac it goes in /usr/local/go. As a beginer you just need to install and you are ready to run the program.

Note: I downloaded Intelij Idea and installed a plugin for Golang.

GOPATH

The GOPATH environment variable specifies the location of your workspace. It is likely the only environment variable you’ll need to set when developing Go code.You can use GOPATH once you are able to run simple applications in Golang.

First GO Program

Create a file named, main.go

// go program need a package mainpackage main// to use any golang functionality we need to import it.import "fmt"func main() { // Println is function of fmt package fmt.Println("Hello Friends")}

// `for` is Go's only looping construct. Here are
// three basic types of `for` loops.
package main
import "fmt"
func main() {
// The most basic type, with a single condition.
i := 1
for i <= 3 {
fmt.Println(i)
i = i + 1
}
// A classic initial/condition/after `for` loop.
for j := 7; j <= 9; j++ {
fmt.Println(j)
}
// `for` without a condition will loop repeatedly
// until you `break` out of the loop or `return` from
// the enclosing function.
for {
fmt.Println("loop")
break
}
// You can also `continue` to the next iteration of
// the loop.
for n := 0; n <= 5; n++ {
if n%2 == 0 {
continue
}
fmt.Println(n)
}
}

// Anonymous functions are useful when you want to define
// a function inline without having to name it.
package main
import "fmt"
// This function `intSeq` returns another function, which
// we define anonymously in the body of `intSeq`. The
// returned function _closes over_ the variable `i` to
// form a closure.
func intSeq() func() int {
i := 0
return func() int {
i += 1
return i
}
}
func main() {
// We call `intSeq`, assigning the result (a function)
// to `nextInt`. This function value captures its
// own `i` value, which will be updated each time
// we call `nextInt`.
nextInt := intSeq()
// See the effect of the closure by calling `nextInt`
// a few times.
//state of nect int is saved
fmt.Println(nextInt())
fmt.Println(nextInt())
fmt.Println(nextInt())
// To confirm that the state is unique to that
// particular function, create and test a new one.
newInts := intSeq()
fmt.Println(newInts())
}

Hello my dear friends. This post will discuss a Creational design pattern Abstract Factory and we will implement it in Golang. There are too many complex definition of Abstract Factory written by very very wide people, but I call my self a normal guy, who just understand the basic language. I will try to explain it in a same way and will implement in Golang.

type AbstractFactory interface {
CreateMyLove()
}

AbstractFactory is a interface which provides a method CreateMyLove(). This a basic thing we need for Abstract Factory.

CreateMyLove() is a factory method.

To explain this all, I will just say without knowing the concrete objects our AbstractFactory can create an objects of my GirlFriend. Now I am ready to create my concrete girlfriend.

Above is a basic implementation for Abstract Factory in Golang. If you need more details Wikipedia is a great place to refer for design patterns understanding. You don’t need to use them every-time. Just use them when you need them most, because they make code reusable but, their implementation is complex. See you soon friends. 🙂

What Are Reflections in Programming?

I went through many articles e.g. Wiki and Quora. These are very nice articles, but what I miss is essence of simplicity for a newbie programmer. So, I will try to explain this in really simple words and we will experiment with Golang.

Let’s go point by point:

Reflection can help you to identify the type of an object at run time.

Yes, type can be printed as string.

Reflection can create an object from string. It means if I give you a configuration file with class names, you can configure your designs with that file by creating objects based on names.

A basic example of reflection, is finding function name from a windows DLL (GetProcAddress). This function helps us to find the function address from it’s name and we can call that address to execute that function.