Skip to main content

Posts

Showing posts from May, 2020

Go #6 - REST Api with Go using net/http

net/http: This is available out of the box in Go language. Package "net/http"  provides HTTP client and server implementations which can be used to make common HTTP requests like GET, POST, PUT, DELETE e.t.c.. While building REST Api's with Go using net/http , here are few methods and interfaces we should understand: type Handler   type Handler interface { ServeHTTP(ResponseWriter, * Request) } - A Handler is responsible for responding to HTTP requests. This interface has only one method ServeHTTP(ResponserWriter, *Request) - You can define your own struct as a Handler which implements  ServeHTTP  method with ResponseWriter and pointer to Request as arguments  package main import ( "net/http" ) type server struct {} func (s * server) ServeHTTP(writer http.ResponseWriter, req * http.Request) { writer.Header().Set( "Content-Type" , "application/json" ) writer.WriteHeader(http.StatusOK) writer...

Go #5 - Receiver Functions in Go

Receiver Functions: Function Receiver sets a method on variables we create. syntax: func (t type ) functionName() {} code: employee.go package employee import "fmt" // Employee struct type employee struct { name string age int salary int } // constructor func NewEmployee(name string , age int , salary int ) * employee { return & employee{ name: name, age: age, salary: salary, } } // print employee func (e employee) ToString() { fmt.Printf( "%s is %d years old with salary %d \n" , e.name, e.age, e.salary) } - Notice the ToString() method in employee.go , it is the receiver's function for employee type - So any new variable of type employee will have access to the ' ToString() ' method main.go package main import "trygo/employee" func main() { rake := employee.NewEmployee( "Rake" , 13 , 4566 ) rake.ToString() } - Calling receiver's function for t...