Golang Cryptography Part II

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…..

Client Code

package main

import (
       "net"
       "fmt"
       "crypto/aes"
)

//this example just tests the data length of block size 16

var key = "12345678912345678912345678912345"

func encryptWriteData(conn net.Conn, data []byte) {
       //creating a block cipher
       block, err := aes.NewCipher([]byte(key))
       if err != nil {
              fmt.Println(err.Error())
       }

       fmt.Println(block.BlockSize())
       mydata := make([]byte,16)

       if len(data) > 16 {
              fmt.Println("Max 16 bytes can be sent in this example...")
              return
       }
       //copy bytes because, even if message is less then 16 bytes, we need 16 bytes.
       copy(mydata,data)

       block.Encrypt(mydata,mydata)

       //sending encrypted data
       conn.Write(mydata)
}

func printDecryptedData(conn net.Conn) {
       data := make([]byte,16)

       _,err :=  conn.Read(data)

       if err != nil {
              fmt.Println(err.Error())
       }

       block, err := aes.NewCipher([]byte(key))
       if err != nil {
              fmt.Println(err.Error())
       }

       mydata := make([]byte,16)

       if len(data) > 16 {
              fmt.Println("Max 16 bytes can be sent in this example...")
              return
       }
       //copy bytes because, even if message is less then 16 bytes, we need 16 bytes.

       copy(mydata,data)

       block.Decrypt(mydata,mydata)

       fmt.Println(string(mydata))

}


func main() {

       conn,err := net.Dial("tcp","127.0.0.1:4908")
       if err != nil {
              fmt.Println(err.Error())
              return
       }

       var input int
       for {
              fmt.Scanf("%d",&input)
              switch input {
              case 1:
                     encryptWriteData(conn,[]byte("Hello Server"))
              case 2:
                     encryptWriteData(conn,[]byte("Password"))
              case 3:
                     encryptWriteData(conn,[]byte("1234"))
              case 4:
                     encryptWriteData(conn,[]byte("Quit"))
              default:
                     encryptWriteData(conn,[]byte("Invalid"))
              }
              printDecryptedData(conn)
       }


}

Server Code

package main

import (
       "net"
       "fmt"
       "crypto/aes"
)



var key = "12345678912345678912345678912345"

func encryptWriteData(conn net.Conn, data []byte) {
       //creating a block cipher
       block, err := aes.NewCipher([]byte(key))
       if err != nil {
              fmt.Println(err.Error())
       }

       mydata := make([]byte,16)

       if len(data) > 16 {
              fmt.Println("Max 16 bytes can be sent in this example...")
              return
       }
       //copy bytes because, even if message is less then 16 bytes, we need 16 bytes.

       copy(mydata,data)

       block.Encrypt(mydata,mydata)

       //sending encrypted data
       conn.Write(mydata)
}

func printDecryptedData(conn net.Conn) int {
       data := make([]byte,16)

       _,err :=  conn.Read(data)

       if err != nil {
              fmt.Println(err.Error())
              return -1
       }

       block, err := aes.NewCipher([]byte(key))
       if err != nil {
              fmt.Println(err.Error())
              return -1
       }

       mydata := make([]byte,16)

       if len(data) > 16 {
              fmt.Println("Max 16 bytes can be sent in this example...")
              return -1
       }
       //copy bytes because, even if message is less then 16 bytes, we need 16 bytes.

       copy(mydata,data)

       block.Decrypt(mydata,mydata)

       k := string(mydata)

       fmt.Println(k)


       if k[:4] == "Quit" {
              conn.Close()
              return -1
       }

       encryptWriteData(conn,[]byte("Server Message"))
       return 0


}

func processRequest(conn net.Conn){
       for {
              if -1 == printDecryptedData(conn) {
                     fmt.Println("Connection closed...")
                     return
              }
       }

}


func main() {
       conn,err := net.Listen("tcp","127.0.0.1:4908")

       if err != nil {
              fmt.Println(err.Error())
              return
       }

       fmt.Println("Server started...")


       for  {
              c, err := conn.Accept()
              if err != nil {
                     fmt.Println(err.Error())
                     return
              }
              go processRequest(c)
       }


       a := 1
       fmt.Scanf("%d",&a)
}

 

 

==========================================================================

Our client and server, are connected over a network, in our case its local, you can change IP of course.  That’s how it works:

  • Client send message to server.
  • Server sends a encrypted reply to it.
  • On Client sending Quit, server quits.

Code is commented, soon I will upload it too my Github. Happy Coding.

Golang Cryptography Part I

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:

  1. Symmetric
  2.  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.

It Provides implementation of, Symmetric, Asymmetric and Message Digests implimentations.

aes : Package aes implements AES encryption (formerly Rijndael), as defined in U.S. Federal Information Processing Standards Publication 197.

cipher:  Package cipher implements standard block cipher modes that can be wrapped around low-level block cipher implementations.

des: Package des implements the Data Encryption Standard (DES) and the Triple Data Encryption Algorithm (TDEA) as defined in U.S. Federal Information Processing Standards Publication 46-3.

dsa: Package dsa implements the Digital Signature Algorithm, as defined in FIPS 186-3.

ecdsa: Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as defined in FIPS 186-3.

elliptic: Package elliptic implements several standard elliptic curves over prime fields.

hmac: Package hmac implements the Keyed-Hash Message Authentication Code (HMAC) as defined in U.S. Federal Information Processing Standards Publication 198.

md5: Package md5 implements the MD5 hash algorithm as defined in RFC 1321.

rand: Package rand implements a cryptographically secure pseudorandom number generator.

rc4: Package rc4 implements RC4 encryption, as defined in Bruce Schneier’s Applied Cryptography.

rsa: Package rsa implements RSA encryption as specified in PKCS#1.

sha1: Package sha1 implements the SHA1 hash algorithm as defined in RFC 3174.

sha256: Package sha256 implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-4.

sha512: Package sha512 implements the SHA-384, SHA-512, SHA-512/224, and SHA-512/256 hash algorithms as defined in FIPS 180-4.

subtle: Package subtle implements functions that are often useful in cryptographic code but require careful thought to use correctly.

tls: Package tls partially implements TLS 1.2, as specified in RFC 5246.

x509: Package x509 parses X.509-encoded keys and certificates.

pkix: Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP.

In coming, pages, I will  discuss most of them in a live example.

Till then, Happy Coding. 🙂

A One Pager Tutorial of Go

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 Website and 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 main
package 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")
}

Run it using, # go run main.go

=============================================
output:
Hello Friends

=============================================

Note: You can also run your programs online @Go Tour.

Go Types and Variables and Scope

Numbers

  • Integers ( uint8, uint16, uint32, uint64, int8, int16, int32 and int64 )
  • Float  : Go has two floating point types: float32 and float64 (also often referred to as single precision and double precision respectively)

Strings

  • “Rajni” , “Friends” are example of Golang string.

Booleans

  • true and false are two states of boolean

Variables

Variables in Golang are same as any other language. But their way of representation is different. They are declared as follows:

var variableName variableType

e.g. Lets write code.

package main

import "fmt"

func main() {
    // declare a variable and assign
    var myInt int = 10
    
    //auto type deduction using :=
    myInt2 := 20

    var myStr string = "Hello"

    myStr2:= "World"

    fmt.Println(myInt + myInt2)
    //string addition works in Golang
    fmt.Println(myStr + myStr2)
}

output:
30
Hello World

Variable Scope

package main 

import "fmt" 

//global variable scope 
var x string = "Hello World Global" 

func main() 
{ 
    fmt.Println(x) f() 
} 

func f() 
{ 
    // local variable scope 
    var x string = "Hello World Local" 
    fmt.Println(x) 
}


Arrays and Slices

var a [4]int //an array of integers size 4
b := [2]string{"Penn", "Teller"} // string array

Array are same as other programming language arrays, but the the way to declare them is a bit different. Lets do an example:

package main

import "fmt"


func main(){
       //array example
       var intarray [4]int
       intarray[0] = 1
       intarray[1] = 2
       intarray[2] = 3
       intarray[3] = 4
       fmt.Println(intarray)

       b := [2]string{"test1", "test2"}
       fmt.Println(b)
       b[0] = "new_test"
       fmt.Println(b)
}

Output:

[1 2 3 4]
[test1 test2]
[new_test test2]

Slices Example

package main

import "fmt"


func main(){
 //array example
 var intarray [4]int
 intarray[0] = 1
 intarray[1] = 2
 intarray[2] = 3
 intarray[3] = 4
 fmt.Println(intarray)

 //example of a slice, we sliced array from 1 to 3 
 b := intarray[1:3]
 fmt.Println(b)

}

Maps In Golang

They are also known as dictionaries, a sample code to use them, :

package main

import "fmt"


func main(){

       a := make(map[string]string)
       a["Myname"] = "Rajni"
       a["MyJob"] = "No Job"

       fmt.Println(a)
       fmt.Println(a["Myname"])
       fmt.Println(a["MyJob"])
       //check non existent
       fmt.Println(a["Noval"])

}

If-else

// Branching with `if` and `else` in Go is
// straight-forward.

package main

import "fmt"

func main() {

       // Here's a basic example.
       if 7%2 == 0 {
              fmt.Println("7 is even")
       } else {
              fmt.Println("7 is odd")
       }

       // You can have an `if` statement without an else.
       if 8%4 == 0 {
              fmt.Println("8 is divisible by 4")
       }

       // A statement can precede conditionals; any variables
       // declared in this statement are available in all
       // branches.
       if num := 9; num < 0 {
              fmt.Println(num, "is negative")
       } else if num < 10 {
              fmt.Println(num, "has 1 digit")
       } else {
              fmt.Println(num, "has multiple digits")
       }

       name := "rajni"

       if name == "rajni" {
              fmt.Println("Hi Rajni")
       } else {
              fmt.Println("Bye Rajni")
       }
}

output:
7 is odd
8 is divisible by 4
9 has 1 digit
Hi Rajni

 

Switch-Case

// _Switch statements_ express conditionals across many
// branches.

package main

import "fmt"
import "time"

func main() {

       // Here's a basic `switch`.
       i := 2
       fmt.Print("Write ", i, " as ")
       switch i {
       case 1:
              fmt.Println("one")
       case 2:
              fmt.Println("two")
       case 3:
              fmt.Println("three")
       }


       switch time.Now().Weekday() {
       
       case time.Saturday, time.Sunday:
              fmt.Println("It's the weekend")
       default:
              fmt.Println("It's a weekday")
       }

       // `switch` without an expression is an alternate way
       // to express if/else logic. Here we also show how the
       // `case` expressions can be non-constants.
       t := time.Now()
       switch {
       case t.Hour() < 12:
              fmt.Println("It's before noon")
       default:
              fmt.Println("It's after noon")
       }

       // A type `switch` compares types instead of values.  You
       // can use this to discover the the type of an interface
       // value.  In this example, the variable `t` will have the
       // type corresponding to its clause.
       whatAmI := func(i interface{}) {
              switch t := i.(type) {
              case bool:
                     fmt.Println("I'm a bool")
              case int:
                     fmt.Println("I'm an int")
              default:
                     fmt.Printf("Don't know type %T\n", t)
              }
       }
       whatAmI(true)
       whatAmI(1)
       whatAmI("hey")
}

Loops

// `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)
       }
}

 

Functions

// _Functions_ are central in Go. We'll learn about
// functions with a few different examples.

package main

import "fmt"

// Here's a function that takes two `int`s and returns
// their sum as an `int`.
func plus(a int, b int) int {

       // Go requires explicit returns, i.e. it won't
       // automatically return the value of the last
       // expression.
       return a + b
}

// When you have multiple consecutive parameters of
// the same type, you may omit the type name for the
// like-typed parameters up to the final parameter that
// declares the type.
func plusPlus(a, b, c int) int {
       return a + b + c
}

func main() {

       // Call a function just as you'd expect, with
       // `name(args)`.
       res := plus(1, 2)
       fmt.Println("1+2 =", res)

       res = plusPlus(1, 2, 3)
       fmt.Println("1+2+3 =", res)
}

 

Closures

Closures are like lambdas, in some languages.

// 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())
}

 

Struct in Golang

// Go's _structs_ are typed collections of fields.
// They're useful for grouping data together to form
// records.

package main

import "fmt"

// This `person` struct type has `name` and `age` fields.
type person struct {
       name string
       age  int
}

func main() {

       // This syntax creates a new struct.
       fmt.Println(person{"Bob", 20})

       // You can name the fields when initializing a struct.
       fmt.Println(person{name: "Alice", age: 30})

       // Omitted fields will be zero-valued.
       fmt.Println(person{name: "Fred"})

       // An `&` prefix yields a pointer to the struct.
       fmt.Println(&person{name: "Ann", age: 40})

       // Access struct fields with a dot.
       s := person{name: "Sean", age: 50}
       fmt.Println(s.name)

       // You can also use dots with struct pointers - the
       // pointers are automatically dereferenced.
       sp := &s
       fmt.Println(sp.age)

       // Structs are mutable.
       sp.age = 51
       fmt.Println(sp.age)
}

Method

// Go supports _methods_ defined on struct types.

package main

import "fmt"

type rect struct {
       width, height int
}

// This `area` method has a _receiver type_ of `*rect`.
func (r *rect) area() int {
       return r.width * r.height
}

// Methods can be defined for either pointer or value
// receiver types. Here's an example of a value receiver.
func (r rect) perim() int {
       return 2*r.width + 2*r.height
}

func main() {
       r := rect{width: 10, height: 5}

       // Here we call the 2 methods defined for our struct.
       fmt.Println("area: ", r.area())
       fmt.Println("perim:", r.perim())

       // Go automatically handles conversion between values
       // and pointers for method calls. You may want to use
       // a pointer receiver type to avoid copying on method
       // calls or to allow the method to mutate the
       // receiving struct.
       rp := &r
       fmt.Println("area: ", rp.area())
       fmt.Println("perim:", rp.perim())
}

Interfaces

// _Interfaces_ are named collections of method
// signatures.

package main

import "fmt"
import "math"

// Here's a basic interface for geometric shapes.
type geometry interface {
       area() float64
       perim() float64
}

// For our example we'll implement this interface on
// `rect` and `circle` types.
type rect struct {
       width, height float64
}
type circle struct {
       radius float64
}

// To implement an interface in Go, we just need to
// implement all the methods in the interface. Here we
// implement `geometry` on `rect`s.
func (r rect) area() float64 {
       return r.width * r.height
}
func (r rect) perim() float64 {
       return 2*r.width + 2*r.height
}

// The implementation for `circle`s.
func (c circle) area() float64 {
       return math.Pi * c.radius * c.radius
}
func (c circle) perim() float64 {
       return 2 * math.Pi * c.radius
}

// If a variable has an interface type, then we can call
// methods that are in the named interface. Here's a
// generic `measure` function taking advantage of this
// to work on any `geometry`.
func measure(g geometry) {
       fmt.Println(g)
       fmt.Println(g.area())
       fmt.Println(g.perim())
}

func main() {
       r := rect{width: 3, height: 4}
       c := circle{radius: 5}

       // The `circle` and `rect` struct types both
       // implement the `geometry` interface so we can use
       // instances of
       // these structs as arguments to `measure`.
       measure(r)
       measure(c)
}

 

These are some basic Golang codes, I just copied the examples and pointed to the link. This part if strictly for coders, who can program and a Golang refresher.

See you soon. Happy Coding.

 

 

Golang Design Pattern Abstract Factory and Factory Method

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.

package main

import "fmt"

// this is my concrete girl friend
type GirlFriend struct {
       nationality string
       eyesColor string
       language string
}

// abstract factory for creating girlfriend
type AbstractFactory interface {
        CreateMyLove() GirlFriend
}


// my indian girlfriend
type IndianGirlFriendFactory struct {

}

// mu korean girlfirend
type KoreanGirlFriendFactory struct {

}

// concrete implementation
func (a IndianGirlFriendFactory) CreateMyLove() GirlFriend {
       return GirlFriend{"Indian" , "Black" , "Hindi"}
}


// concrete implementation
func (a KoreanGirlFriendFactory) CreateMyLove() GirlFriend {
       return GirlFriend{"Korean" , "Brown" , "Korean"}
}


// main factory method
func getGirlFriend(typeGf string) GirlFriend {

       var gffact AbstractFactory
       switch typeGf {
       case "Indian":
              gffact = IndianGirlFriendFactory{}
              return gffact.CreateMyLove()
       case "Korean":
              gffact = KoreanGirlFriendFactory{}
              return gffact.CreateMyLove()
       }
       return GirlFriend{}
}

func main(){

       var typeGf string
       fmt.Scanf("%s", &typeGf)
       a := getGirlFriend(typeGf)

       fmt.Println(a.eyesColor)

}

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.  🙂

Playing with Reflections in Golang

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.

// declare a type PGNSI
typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);

//declare a variable of type PGNSI
   PGNSI pGNSI;
   SYSTEM_INFO si;

   
   // get address of funtion GetNativeSystemInfo and store in pGNSI
   pGNSI = (PGNSI) GetProcAddress(handle, "GetNativeSystemInfo");
   if(NULL != pGNSI)
   {
      // call function
      pGNSI(&si);
   }

don’t get confused above code in in C language just don’t try to run it, it’s just for explanation of concept.

Reflections in Golang

Golang also implements this beautiful feature of reflection. There is a sweet blog , Laws Of Reflection.

Type and Interface in Golang

Before diving into reflections, we need a little backgroung on types and interfaces. “Go is a statically typed language“, yes one type cannot be automatically typed in to another.

e.g.

package main
import "fmt"

func main() {

       type MyInt int
       var a int = 0
       var b MyInt = 10

       fmt.Println("Before")
       fmt.Println(a)
       fmt.Println(b)

       //a = b // .\main.go:18: cannot use b (type MyInt) as type int in assignment
       a = int(b) // good assignment

       fmt.Println("After")
       fmt.Println(a)
       fmt.Println(b)
}

Although MyInt and int are same kind of type, but we cannot assign one to another.

Interfaces in Go 

Interfaces are special kind of type, e.g.

// Reader is the interface that wraps the basic Read method.
type Reader interface {
       Read(p []byte) (n int, err error)
}

// Writer is the interface that wraps the basic Write method.
type Writer interface {
       Write(p []byte) (n int, err error)
}

//an empty interface
type EmptyIface interface {

}
  • Every type in Golang implements empty interface.
  • A non empty interface consists of rule or method, any type abiding that rule becomes of interface type. e.g.
package main
import "fmt"

// Reader is the interface that wraps the basic Read method.
type Reader interface {
       Read(p []byte) (n int, err error)
}


type MyInt int

// MyInt implements Reader interface
func (a MyInt) Read(p []byte) (n int, err error) {
       return 10 ,nil
}

func main() {

       var b MyInt = 10

       p,_ := b.Read(nil)

       fmt.Println(p)

}

We don’t need type assertions for empty interface.

package main
import "fmt"


type Empty interface {

}

func main() {
       var data empty = 10
       fmt.Println(data)
}

As we are clear with types and interfaces let’s begin reflections.

Reflections

Go implements it’s reflection functionality in Package Reflection. The package consists of many routines and types let’s learn by using it.

reflect.TypeOf()

reflect.TypeOf() return a Type variable, which represents a Go Type. We can see this in output of the code below.

package main
import "fmt"
import "reflect"

type TestStruct struct {
       test int
}


type Inface interface {
       read()
}
func (k TestStruct) read() {

}

func main() {

       var integer int = 10
       var structure TestStruct
       var interfaceblank Inface
       var interfacew Inface  = TestStruct{}
       var interfacep Inface  = &TestStruct{}
       var myarray [6]int

       fmt.Println("=============================================================")
       var test reflect.Type =  reflect.TypeOf(integer)
       fmt.Println("output integer: ",test)
       fmt.Println("output integer kind: ",test.Kind())
       fmt.Println("=============================================================")


       test = reflect.TypeOf(structure)
       fmt.Println("output structure: ",test)
       fmt.Println("output structure kind: ",test.Kind())
       fmt.Println("=============================================================")

       test = reflect.TypeOf(interfaceblank)
       fmt.Println("output interfaceblank: ",test)
       //fmt.Println("output integer kind: ",test.Kind()) // panics for nil interface
       fmt.Println("=============================================================")

       test = reflect.TypeOf(interfacew)
       fmt.Println("output interfacew: ",test)
       fmt.Println("output interfacew kind: ",test.Kind())
       fmt.Println("=============================================================")

       test = reflect.TypeOf(interfacep)
       fmt.Println("output interfacep: ",test)
       fmt.Println("output interfacep kind: ",test.Kind())

       test = reflect.TypeOf(myarray)
       fmt.Println("output myarray: ",test)
       fmt.Println("output myarray kind: ",test.Kind())
       fmt.Println("output myarray elem: ",test.Elem())
}

=============================================================
output integer: int
output integer kind: int
=============================================================
output structure: main.TestStruct
output structure kind: struct
=============================================================
output interfaceblank: 
=============================================================
output interfacew: main.TestStruct
output interfacew kind: struct
=============================================================
output interfacep: *main.TestStruct
output interfacep kind: ptr
=============================================================
output myarray: [6]int
output myarray kind: array
output myarray elem: int

Type is the representation of a Go type.

A Kind represents the specific kind of type that a Type represents. The zero Kind is not a valid kind.

An Elem() will give type of element inside a Type. It panics if  type’s kind is not array, slice, channel, map or pointer.

Reflection A Live Code Example

 

package main

import (

       "fmt"

       "reflect"

)

type MyStruct struct {

       Name string `tag_name:"Name"`

       Wife  string `tag_name:"Wife"`

       Age       int    `tag_name:"Age"`

}

func (f * MyStruct) reflectIt() {

       // take out type inside *f

       val := reflect.ValueOf(f).Elem()

       // iterate over all the fields inside structure

       for i := 0; i < val.NumField(); i++ {
// read value of field

valueField := val.Field(i)

//read type of field

typeField := val.Type().Field(i)

// read tag of field

tag := typeField.Tag

fmt.Printf("Field Name: %s,\t Field Value: %v,\t Tag Value: %s\n", typeField.Name, valueField.Interface(), tag.Get("tag_name"))

}

}

func main() {

f := &MyStruct{Name: "Rajni",Wife:"Sakshi",Age:30,}

f.reflectIt()

}

output:
==============================================================================
Field Name: Name, Field Value: Rajni, Tag Value: Name
Field Name: Wife, Field Value: Sakshi, Tag Value: Wife
Field Name: Age, Field Value: 30, Tag Value: Age

The code above explains the reflection in few lines. Will be back with more topics. See you soon.

Happy Coding.

XML Applications Golang

Hello everyone, in my last blog, Golang SQL JSON

I used JSON for transferring data among application and service, now using same code with a small tweak we can use XML in place of JSON.

The code now looks like this:

Main.go

package main

import (
       "net/http"
       "fmt"
       "io"
       _ "github.com/go-sql-driver/mysql"
       "database/sql"

       "strconv"
       "encoding/xml"
)

var appdatabase *sql.DB



type Userstruct struct {
       Username string
       Age string
       Salary string
}


func insertInDatabase(data Userstruct) error {
       age,_ := strconv.Atoi(data.Age)
       salary,_ := strconv.Atoi(data.Salary)
       _, err := appdatabase.Exec("INSERT INTO emptable(name, age, salary) VALUES(?, ?, ?)", data.Username , age, salary)
       return err

}

func getFromdatabase(uname string, w http.ResponseWriter) error{

       out := Userstruct{}

       err := appdatabase.QueryRow("SELECT * FROM emptable WHERE name=?", uname).Scan(&out.Username, &out.Age, &out.Salary)

       if err != nil {
              return err
       }

       enc := xml.NewEncoder(w)

       err = enc.Encode(&out)

       return err
}

func userAddHandler(w http.ResponseWriter, r *http.Request) {


       //make byte array
       out := make([]byte,1024)

       //
       bodyLen, err := r.Body.Read(out)

       if err != io.EOF {
              fmt.Println(err.Error())
              w.Write([]byte("{error:" + err.Error() + "}"))
              return
       }

       var k Userstruct

       fmt.Println(string(out))

       err = xml.Unmarshal(out[:bodyLen],&k)


       if err != nil {
              w.Write([]byte("{error:" + err.Error() + "}"))
              return
       }

       err = insertInDatabase(k)

       if err != nil {
              w.Write([]byte("{error:" + err.Error() + "}"))
              return
       }

       w.Write([]byte(`{"error":"success"}`))

}

func userGetHandler(w http.ResponseWriter, r *http.Request) {

       type Userstruct struct {
              Username string
       }

       //make byte array
       out := make([]byte,1024)

       //
       bodyLen, err := r.Body.Read(out)

       if err != io.EOF {
              fmt.Println(err.Error())
              w.Write([]byte(`{"error":"bodyRead"}`))
              return
       }

       var k Userstruct

       //err = json.Unmarshal(out[:bodyLen],&k)

       err = xml.Unmarshal(out[:bodyLen],&k)

       if err != nil {
              w.Write([]byte(err.Error()))
              return
       }

       err = getFromdatabase(k.Username, w)

       if err != nil {
              w.Write([]byte("{error:" + err.Error() + "}"))
              return
       }


}



func StartService(port string) {

       http.HandleFunc("/adduser", userAddHandler)
       http.HandleFunc("/getuser", userGetHandler)
       http.ListenAndServe(":" + port, nil)
}

func main() {

       var err error
       appdatabase, err = sql.Open("mysql", "root:asdf1234@/employee")

       if err != nil {
              panic(err.Error())
       }
       err = appdatabase.Ping()
       if err != nil {
              fmt.Println(err.Error())
       }

       StartService("8090")
}

In place of Golang json encoder, I am using xml encoder and rest is same in complete code.

For testing I am again using Advance REST client.

Image of my test can be seen below:

This is for “adduser” functionality.

No we are sending XML raw payload.

capture

This is for “getuser” functionality.

No we are sending XML raw payload and getting XML response.

capture

Have a look, it’s so easy in Golang to change the APIs, whether it’s XML or JSON. You can be a rock star in just few lines of code.

So, this one ends here.

See You Soon.

Happy Coding.

Love,

Rajni

 

 

Using MySQL and JSON with Golang, Small Tutorial

Introduction

“Hello everyone”. REST API is the common web service mechanism that we can find on any system. Using a web service, applications can communicate with each other. Like function calling mechanism. 


APIs can handle data and save it in Database. I will use MySQL. So, I will cover following in this tutorial.

  • Basic HTTP server handling JSON requests.
  • Using JSON inside Golang.
  • Saving and retrieving Data from MySQL.

Setup and Dependencies:

  • Go must be installed on your systems.
  • MYSQL server must be installed.
  • Advanced REST Client, chrome extension.

Note: I will not use any framework. Because frameworks limits the learning. So, be ready for some raw coding.


Getting MySQL connector for Golang:


Before configuring your connector.

  1. Your GOPATH  must be configured.
  2. Now run the following command :  go get github.com/go-sql-driver/mysql

This will have your MySQL connector configured.


This image shows, that go-sql-driver.mysql is installed in my GOPATH.

Getting Your Hands Dirty:

JSON request and response

Create a sample application in golang:

package main


import "net/http"import "strings"import "fmt"


var routes map[string]RouteInterface

func routeHandler(w http.ResponseWriter, r *http.Request) {
//just printing the stuff
       fmt.Println(r)
       b := make([]byte, 1024)
       r.Body.Read(b)
       fmt.Println(string(b))
       fmt.Println(r.Method)
       fmt.Println(string(strings.Join(r.Header["Content-Type"],"")))
       w.Write([]byte("Hello Friends, Wecome to My Blog"))

}

func StartService(port string) {

       http.HandleFunc("/", routeHandler)
       http.ListenAndServe(":" + port, nil)
}

func main() {
        StartService("8090")
}

Run the code using ,

go run main.go

capture

Open Advance Rest Client extension in chrome.

A request was made to http://localhost:8090 and Content-Type was set to JSON.

The Golang application sent, Hello Friends, Wecome to My Blog as responseto the request.

The main.go will print:

&{POST / HTTP/1.1 1 1 map[Content-Type:[application/json] Content-Length:[16]] 0xc0420604c0 16 [] false localhost:8090 map[] map[] map[] [::1]:60563 / 0xc042060500}
json : {“a”:”b”}
POST
application/json

The above program was just a basic of JSON communication. Now let’s begin some cool stuff and create a small application which uses:

  • A service created in Golang
  • MySQL database to save and retrieve data.
  • JSON

###############################################################

Let’s Begin our small application:

Let’s do a simple Simple Design First, following will be our application flow:

Step 1:

Client will send a JSON request,  http://localhost:8090/adduser

{“Username”:”Rajni” , “Age”:”31″, “Salary”:”500000000000″}

Step 2:

Server will receive and validate request, and will add it to database.

Step 3:

Client will send request, http://localhost:8090/getuser

{“Username”:”Rajni”}

Step 4:

Server will return: {“Username”:”Rajni” , “Age”:”31″, “Salary”:”500000000000″}

###############################################################

Create a database and table in MySQL

mysql> create database employee;
Query OK, 1 row affected (0.01 sec)

mysql> use employee
Database changed

mysql> CREATE TABLE `employee`.`new_table` (`name` VARCHAR(45) NOT NULL,`age` INT NOT NULL,`salary` INT NOT NULL,PRIMARY KEY (`name`));

###############################################################

Let’s Write Back-End

Main.go

package main

import (
       "encoding/json"
       "net/http"
       "fmt"
       "io"
       _ "github.com/go-sql-driver/mysql"
       "database/sql"
       "strconv"
)

// _ in package means this package will not cause error if unused

//database instance
var appdatabase *sql.DB


// user struct
type Userstruct struct {
       Username string
       Age string
       Salary string
}


func insertInDatabase(data Userstruct) error {
       //convert age to int
       age,_ := strconv.Atoi(data.Age)

       //convert salary to int
       salary,_ := strconv.Atoi(data.Salary)

      //execute statement
       _, err := appdatabase.Exec("INSERT INTO emptable(name, age, salary) 
                    VALUES(?, ?, ?)", data.Username , age, salary)
       return err

}

func getFromdatabase(uname string, w http.ResponseWriter) error{

       out := Userstruct{}

       err := appdatabase.QueryRow("SELECT * FROM emptable WHERE name=?", uname).
                            Scan(&out.Username, &out.Age, &out.Salary)

       if err != nil {
              return err
       }
       
       //create json encoder and assign http response , 
          //which implements the IO interface 
       enc := json.NewEncoder(w)

       err = enc.Encode(&out)

       return err
}

func userAddHandler(w http.ResponseWriter, r *http.Request) {


       //make byte array
       out := make([]byte,1024)

       //
       bodyLen, err := r.Body.Read(out)

       if err != io.EOF {
              fmt.Println(err.Error())
              w.Write([]byte("{error:" + err.Error() + "}"))
              return
       }

       var k Userstruct

       err = json.Unmarshal(out[:bodyLen],&k)


       if err != nil {
              w.Write([]byte("{error:" + err.Error() + "}"))
              return
       }

       err = insertInDatabase(k)

       if err != nil {
              w.Write([]byte("{error:" + err.Error() + "}"))
              return
       }

       w.Write([]byte(`{"error":"success"}`))

}

func userGetHandler(w http.ResponseWriter, r *http.Request) {

       type Userstructlocal struct {
              Username string
       }

       //make byte array
       out := make([]byte,1024)

       //
       bodyLen, err := r.Body.Read(out)

       if err != io.EOF {
              fmt.Println(err.Error())
              w.Write([]byte(`{"error":"bodyRead"}`))
              return
       }

       var k Userstructlocal

       err = json.Unmarshal(out[:bodyLen],&k)


       if err != nil {
              w.Write([]byte(err.Error()))
              return
       }

       err = getFromdatabase(k.Username, w)

       if err != nil {
              w.Write([]byte("{error:" + err.Error() + "}"))
              return
       }


}



func StartService(port string) {

       http.HandleFunc("/adduser", userAddHandler)
       http.HandleFunc("/getuser", userGetHandler)
       http.ListenAndServe(":" + port, nil)
}

func main() {
       var err error
       appdatabase, err = sql.Open("mysql", "root:asdf1234@/employee")
       if err != nil {
              panic(err.Error())
       }
       err = appdatabase.Ping()
       if err != nil {
              fmt.Println(err.Error())
       }

       StartService("8090")
}

The above code is a basic implementation of JSON service which add data to database. To test this I will use ARC chrome extension.

Pasting some images below.

This shows a request is sent to:

http://localhost:8090/adduser

and

{“error”:”success”} is returned.

capture

To check whether user is added, either do a select SQL query or run the following link:

http://localhost:8090/getuser as shown in image below.

capture

Here, we got this. We can see the user in get request.

Summary

JSON can be used to transfer data on the web in a really well structured format. MySQL is a good free database to host our application data.

And  Golang has made it so east to work upon in form of micro services, that with it we can easy create micro services and deploy on tools like Docker.

So, my love for Golang has just begun and hope you will also enjoy the blog.

Good Night, God Bless. 🙂

Regards,

Rajni Kant Sharma