Golang Interface Simplified

What is Interface?

Interface is used for abstraction. It contains one or more method signatures. Below is an example of how we define interface.

type Human interface {
	speak()
}

Why we use interface?

In simple term interfaces are the contract for the methods for different structure type. To increase the code readability and maintenance we use interface. Let’s say there is Person datatype in my application and all the methods mentioned above actually implement the Person data type.

type Person struct {
	First string
	Last  string
}

Now let’s say the method mentioned in the interface actually implement the Person struct

func (p Person) speak() {
	fmt.Println("I am Person ", p.First)
}

Now the interesting part our software got a new requirement of adding another data type called SecretAgent.

type SecretAgent struct {
	Person Person
	Org    string
}

Now we define another method speak() for the SecretAgent data type.

func (s SecretAgent) speak() {
	fmt.Println("I am secret agent ", s.Person.First)
}

Now we can take the help of interface and the power of abstraction. We define a function that will take the interface and call the speak method.

func Earthling(h Human) {
	fmt.Println("Hey there I am from planet Earth")
	h.speak()
}

Understand what happened above? The Indian function take the human interface and call the speak method and we don’t have to specify for which data type the speak is going to work it will be managed by the go interfaces. So, it reduced a lot of hard coding and our design is future ready to accept more data type.

Let’s see the main function.

func main() {
	sa1 := SecretAgent{
		Person: Person{First: "James", Last: "Bond"},
		Org:    "MI6",
	}
	sa2 := SecretAgent{
		Person: Person{First: "Ajit", Last: "Doval"},
		Org:    "RAW",
	}
	p1 := Person{First: "Dr.", Last: "Strange"}

	Earthling(sa1)
	Earthling(sa2)
	Earthling(p1)
}

Daily Learning: Computer Networks – Sliding Window Protocol

Go Back N

If there is a packet lost in the receiver side then it is going to discard the subsequent packets and re transmit the the entire window means it is going back N values and re transmit the the packets

  • Sender window size is go back N is N
  • Receiver Window size is always 1.
  • Acknowledgement –
    • Cumulative – One acknowledgement is used for many packets.
      • Adv – Traffic is low
      • Dis Adv – Reliability low
    • Independent – One acknowledgement is used for one packet.
      • Adv – Reliability is high
      • Dis Adv – Traffic is high

Relationship Between Window Sizes and Sequence Numbers

Minimum sequence numbers required in GBN = N + 1

Bits Required in GBN = log2 (N + 1)

If the sequence number is N then Sender window size is N – 1. Receiver window size is 1.

If the bit is K then sequence number 2^k, Sender Window size is 2^k – 1. Receiver window size is 1.

Formula

  • Maximum window size = 1 + 2 * a [a=Tp/Tt]
  • Minimum sequence numbers required = 1 + 2 * a
  • Number of Bits in Sequence Number Field = log2(1+2a)

Selective Repeat

Selective Repeat

This protocol(SRP) is mostly identical to GBN protocol, except that buffers are used and the receiver, and the sender, each maintains a window of size. Here we only re transmit the lost packet not the entire window again.

  • Sender window size is greater than 1 (Ws > 1)
  • Receiver window size = sender window size (Wr == Ws)
  • Acknowledgements are independent. If bits in the packets are corrupted then SR will send a negative acknowledgement.

Note – If N is the size of sequence number field in the header in bits, then we can have 2N sequence numbers.

Window Size = min(1+2*a, 2^N)

Stop & WaitGBNSR
Efficiency1/1+2aN/1+2aN/1+2a
Buffer1+1N+1N+N
Segment Number1+1N+1N+N
Retransmission1N1
Bandwidthlowhighmedium
CPUlowmediumhigh
Implementationsimplemediumcomplex

How to get environment variable value with the help of struct tags?

Struct Tags

Go struct tags are annotations that appear after the type in a Go struct declaration. Each tag is composed of short strings associated with some corresponding value.

A struct tag looks like this, with the tag offset with backtick “ characters:

type User struct {
	Name string `example:"name"`
}

We can write other go code to examine the tags and do some cool stuff with it. The tags don’t change the main go struct behavior.

How to get environment variable value by the struct tags?

The classic example of populating the struct fields by the environment variable is by doing os.Getenv() again and again and manually populating the values. But in this case the work is to much repeat and error prone if the struct is too large.

type EmailConfig struct {
	Email string `env:"EMAIL"`
}

func main() {
	cfg := EmailConfig{
		Email: os.Getenv("EMAIL")
	}
}

But can we improve it? Yes we can by using the reflection

import (
	"fmt"
	"os"
	"reflect"
)

type Config struct {
	Email    string `env:"EMAIL"`
}

const tagName = "env"

func LoadConfig(q *Config) {
	v := reflect.ValueOf(q).Elem()
	if v.Kind() == reflect.Struct {
		val := reflect.TypeOf(q).Elem()
		for i := 0; i < val.NumField(); i++ {
			field := val.Field(i)
			tag := field.Tag.Get(tagName)
			fmt.Printf("field : %v | tagName : %v\n", field.Name, tag)
			envVal := os.Getenv(tag)
			reflect.ValueOf(q).Elem().FieldByName(field.Name).Set(reflect.ValueOf(envVal))
		}
	}
}

func main() {
	var cfg Config
	LoadConfig(&cfg)
	fmt.Println(cfg)
}
  • Here we have initiated a empty cfg structs and passed the reference in the LoadConfig function.
  • In the LoadConfig function we have iterated over the struct field.
  • we extract the tag fields and set the field values with the environment variable value extracted by the tag name.

Daily Learning: Computer Networks – Delay in Transmission & Flow Control & Stop and Wait

Delays

There are many types of delays –

  1. Transmission Delay – The time taken for host to put the entire packet in the line is transmission delay. If the first bit of the packet on the the line at time t1 and the last bit of the packet is put on the line at time t2, so the transmission delay of the packet is (t2 – t1). We define transmission delay as Tt = L/B (L = Length of packet, B = Bandwidth) Notation Data
  2. Propagation Delay – The time taken for a bit to travel from source to destination is propagation delay. Tp = d/v (d = Distance of host to destination, v = velocity of the packet)
  3. Queuing delay – Packets are received in the receiver and sit in a queue until all packet come it is called queuing delay.
  4. Processing Delay – Packets are taken from the queue and taken to the processor for processing that is called processing delay.

Flow Control

Sometime wile sending data from sender to receiver the other end there may be queue is full in that case the later packets will be discarded for that we use stop and wait protocol. Here we send a packet and from other end it sends an acknowledgement for this there are some transmission d delay and inefficiency.

Stop and Wait Automatic Repeat Request

  • ARQ (Automatic Repeat Request) – If a sender sends a data and the packet is lost then the receiver won’t send the acknowledgement at all and the system will get into a deadlock. In order to break the deadlock we use a Timeout Timer and if no acknowledge comes in the that time we resend the packet again.
  • Duplicate Packet Problem – If the acknowledgement is lost and then the sender will again assume that the data is lost and the sender will resend the packet and receiver will re process it. In order to overcome the problem we use sequence number to the data.
  • Missing Packet Problem – If the sender sends a packet p1 and the acknowledgement A got delayed for that sender again sends the packet p1 and got the acknowledgement A then it sends packet p2 and the packet got lost but the first acknowledgement for p1 got arrived now the sender will think that the packet p2 got send successfully. In order to solve the problem we use a acknowledgement number.
  • Some time the sender may send a lot of data and the receiver may not that much capable of handling the data.
  • So the here the sender first send one data packet and wait for a particular time the acknowledgement from the receiver.
  • If the acknowledgement comes in that time or before time then good.
  • Otherwise the sender then automatically resend the data.

Properties

  • When the receiver receives the packet it send acknowledgement for the next packet(not the packet that was received.)
  • In this method there is only one packet the channel always so the when a packet is sent successfully we can reuse the sequence number of that packet again.

Formulas

  • Total Time – Tt + 2 * Tp [Tt = Transmission time for data, Tp = Propagation time]
  • Efficiency(η) – 1 / 1 + 2a [a = Tp / Tt]
  • Throughput or Effective Bandwidth or Bandwidth Utilization – η * B [η = Efficiency, B = bandwidth]

Stateful vs Stateless Application

State – It is the session data that is been generated at the time of a client connects to a server.

  • Stateful – In stateful architecture let’s imagine a scenario of a eCommerce website that has 3 servers and there are 3 user connected to three servers and all the user session is store in the servers accordingly. Now let’s imagine a scenario of one of the three server goes down and all the state information about the users that were associated with it also lost. Now all that users have to do all the process again after establishing connection to a new server. So that’s a big issue in scalability and availability.
  • Stateless – In stateless architecture all the state information about the client is been stored in the shared storage connected to all the servers. Now let’s suppose a server goes down and and because all the state information is shared so if a client establish a connection with new server all the state information can be restored from the shared storage.

In conceptual we are going stateless but basically the we cannot eliminate the state entirely. There must be some place we are storing the states. We call it shared storage.

To be continued

Daily Learning: Computer Networks – Supernetting or Aggregation

In the routing table there is entry for all the sub networks present in a network. And as the network increase the size of the routing table also increase. For this the router combine multiple networks to form a bigger network.

Rules

  1. IP addresses must be contiguous.
  2. All network should be of same size(the size also should be 2^n).
  3. The first network ID should be divisible by the size of the block(number of host).
200.1.0.0
200.1.1.0
200.1.2.0
200.1.3.0

Let’s see the IP address can form a supernet or not. Ans is yes they can. because-

  1. All are contiguous.
  2. All network of same size.
  3. Total number of host is 4 * 2^8 then the first IP address is divisible.

Supernet Mask

We put all 1 in the place of Network ID and all 0 in the place of Host ID.

      200.1.00000000.00000000
      200.1.00000001.00000000
      200.1.00000010.00000000
      200.1.00000011.00000000
------------------------------------
    255.255.11111100.00000000   Mask

Supernet Mask is - 255.255.252.0

Daily Learning: Computer Networks – Classless Inter Domain Routing(CIDR)

In classfull representation Every network used to get same amount of host regarding of the class of the network. But that is a waste in many cases where if a user need 2^14 host and buy the class B network then 49152 network are wasted. To counter this situation IANA came up with a new technique –

CIDR

It is also a 32 bit number but it has a special number which represents the number of bit present in block ID.

a.b.c.d/n
20.10.50.100/20

Here the number of Host present in the network is 2^(32-n) or here 2^12.

  • Rules
    1. All the IP addresses re contiguous. Means there can’t be any fragmentation.
    2. Block size must be power of 2(2^n). If the block size is 2^5 then the Host ID will contain 5 bits and the Block ID will be 27 bits.
    3. First IP address must be evenly divisible by the size of the block. Means the least significant part should always start with zeroes in Host ID.
    • Check whether 100.1.2.32 to 100.1.2.47 is a valid IP address block or not?
      1. All the IP addresses are contiguous.
      2. Total number of IP addresses in the Block = 16 = 2^4
      3. 1st IP address: 100.1.2.00100000 . Since, Host Id will contains last 4 bits and all the least significant 4 bits are zero. Hence, first IP address is evenly divisible by the size of the block.

Subnetting

Suppose our CIDR address is 20.30.40.10/25 means the host ID is 7 bit 20.30.40.00001010

So the network ID will be 20.30.40.00000000 . Now If I want to divide the network in 2 part I will need to use 1 bit from the host ID. So the total ID part is now 26. 1st part : starting address is 20.30.40.00000000(20.30.40.0/26) & the direct broadcast address is 20.30.40.00111111(20.30.40.63/26).

2nd Part : Starting address is 20.30.40.01000000(20.30.40.64/26) & the direct broadcast address is 20.30.40.01111111(20.30.40.127/26). Same as if we wanted to divide the network in 4 parts we will have we will have ID part will be 27.

Daily Learning: Computer Networks – Casting & Subnet & Subnet Mask

Casting

Sending some data from one host to another host is called casting. There are three type of casting –

  1. Unicast – When we are sending message from one host to one host. The packet consist of | data | Source Address | Destination Address |
  2. Broadcasting –
    1. Limited Broadcasting – When a host want to send a packet to everyone in the same network then it use Limited Broadcasting. The packet consist of | data | Source Address | 255.255.255.255 |
    2. Direct Broadcasting – When we are sending a message from one host of one network to all the host of other network then we use Directed Broadcasting. The packet consist of | data | Source Address | 20.255.255.255 |
  3. Multicast – Transmitting data from one source host to a particular group of hosts that are interested in receiving the data is called Multicast. It is also called one to many transmissions.

Subnet

When a bigger network is divided into sub network to maintain security is called subnetting.
In order to divide the network into two parts you need select 1 bit from 8 bit of the host ID part.

The above network is class C network and the NID is 193.1.2.0 and we divide the network into two parts. Subnet 1 = we get the range 193.1.2.00000000(193.1.2.0) – 193.1.2.01111111(193.1.2.127). Here the 193.1.2.0 is the subnet ID and 193.1.2.127 is the Direct Broadcasting address. Subnet 2 = we get the range 193.1.2.10000000(193.1.2.128) – 193.1.2.11111111(193.1.2.255). Here the 193.1.2.128 is the subnet ID and 193.1.2.255 is the Direct Broadcasting address.

Subnet Mask

Suppose we divide a Class C network with 4 subnets. So in order to identify which packet belongs to which network we use subnet mask. It is a 32 bit number consist of 0 & 1. 1 = Network ID & Subnet ID 0 = Host ID So, for a IP address 200.1.2.30 the Subnet Mask is –

11111111.11111111.11111111.11000000 
or
255.255.255.192

So, to identify which IP belongs to which subnet use use bitwise and operation on the subnet mask and the IP address.

    11111111.11111111.11111111.11000000
&&  11001000.00000001.00000010.00011110
-----------------------------------------------------
    11001000.00000001.00000010.00000000

The address belongs to subnet 1.

11001000.00000001.00000010.00000000 
or
200.1.2.0

Internally there is a routing table which helps forward the packet.

Note: Some cases NID match with two entries, in that case the interface having longest subnet mask(More 1’s) is selected.

Daily Learning: Computer Networks – IP Address & DNS

IP Address

When we type google.com in our web browser it is converted into IP addresses and then it reach to the desired google network and host and specific port to get the web page.

An IP address consists of two part –

  1. Network ID
  2. Host ID

The size of IP address is 32 bit.

Generation

  • 1st Gen – In 1980 the IP address was divided into 8 bit or Network ID and 24 bit of Host ID but as people starts using computer more the requirement got more.
  • Classful System – We have divided the IP address into various classes –

Class A we take the first bit, Class B we take the first 2 bit, similarly in Class C we take the first 3 bit and so on till Class E.

ClassStarts WithNetwork BitHost BitTotal NetworksHost per NetworkNetwork Range
Class A01 + 72412816M1-126
Class B102 + 141616K65K128-191
Class C1103 + 21820M256192-223
Class D1110Reserved For MulticastN/AN/AN/A224-239
Class E11111Reserved For ExperimentN/AN/AN/A240-255

What is dotted decimal representation?

If we divide the IP address in four parts(8 bits) and we convert the 8 bit into decimal and we put “.” in between it is called dotted decimal representation. e.g. – 127.0.0.1

Note : We can configure total (number of host – 2) per network.

  • suppose we have a network 11.0.0.0, 14.0.0.0. Whenever there is all 0 in the host ID it represents the network itself. That’s why we don’t use first IP address as a valid IP address for a host.
  • 255.255.255.255 is assigned as Limited Broadcast Address. So it can’t be assigned to any host.
  • 255 as host ID is assigned as Direct Broadcasting Address. So it can’t be assigned to any host. e.g – (NID).255.255.255

DNS

What is DNS overhead?

For converting the domain name into IP address we go to DNS(Domain Name Service) Server of the ISP(Internet Service Provider) and if it doesn’t know the IP then there are three hierarchy servers that helps –

  1. Root Server
  2. TLD Server(Top Level Domain)
  3. Name Server

Actually we don’t do it every time we visit a website after conversion we store the IP address locally in our computer.

Daily Learning: Computer Networks – NAT(Network Address Translation)

In the past we used to use IPv4 which has limited number of host that can be given the IP addresses. For that we use NAT to solve the problem.

Let’s see how it works –

  • First ISP gives you a valid public IP address and that is being setup in the router.
  • The router assign a new private IP address to the new hosts that joins the network.
  • The private IP addresses are reserved so no one else can connect to you.
  • When you send a Ethernet packet to the outside of the world then you first send the packet to the router then it translate the private IP to public IP then sends the packet.
  • When a packet comes from outside world then it first comes to the router then router translate the public IP to private IP then it uni cast the packet to the host in the LAN.

Note – Your neighbor router connected devices could have the same private IP addresses but that won’t effect you network because the IP are all private.