How to add packages in Golang

How to add packages to golang project


Golang is a programming language developed by Google. It can used to create cloud services, web , CLI tools etc. The first step to use Go is download and install the SDK.

Packages

There are plenty of packages ready to serve your needs in Golang directory. Most of them are opensource and all you have to do is get the required from Package page and add to the project using go get command as follows.

 go get gorm.io/driver/sqlite

Create REST API using gin in Golang

How to create simple REST API using golang and gin package


Golang is a programming language developed by Google. It can used to create cloud services, web , CLI tools etc. The first step to use Go is download and install the SDK.

Basic setup

To build basic API in Golang we need two packages.

go get github.com/gin-gonic/gin

Gin help us to build API routes . Local JSON data is used for the demonstration. In the main.go file add the following

package main

import  
("github.com/gin-gonic/gin"
"net/http")
 
// album represents data about a record album.
type album struct {
    ID     string  `json:"id"`
    Title  string  `json:"title"`
    Artist string  `json:"artist"`
    Price  float64 `json:"price"`
}

// albums slice to seed record album data.
var albums = []album{
    {ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
    {ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
    {ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}

func index(c *gin.Context){
	c.JSON(200,gin.H{"message": "hi there!"})
}

func getAlbums(c *gin.Context) {
    c.IndentedJSON(http.StatusOK, albums)
}

// postAlbums adds an album from JSON received in the request body.
func postAlbums(c *gin.Context) {
    var newAlbum album

    // Call BindJSON to bind the received JSON to
    // newAlbum.
    if err := c.BindJSON(&newAlbum); err != nil {
        return
    }

    // Add the new album to the slice.
    albums = append(albums, newAlbum)
    c.IndentedJSON(http.StatusCreated, newAlbum)
}

// getAlbumByID locates the album whose ID value matches the id
// parameter sent by the client, then returns that album as a response.
func getAlbumByID(c *gin.Context) {
    id := c.Param("id")

    // Loop through the list of albums, looking for
    // an album whose ID value matches the parameter.
    for _, a := range albums {
        if a.ID == id {
            c.IndentedJSON(http.StatusOK, a)
            return
        }
    }
    c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
}

func main(){
	r:=gin.Default()
	r.GET("/",index)
	r.GET("/albums",getAlbums)
	r.POST("/albums", postAlbums)
	r.GET("/albums/:id", getAlbumByID)
	r.Run()
}

Here we created a gin instance which can be used to create API route. We also defined handler functions which handle the request.

:= is the short hand in Golang for creating variables

Run the project

By using go run . or go run main.go can execute the program.

How to Containerize Golang app with Docker

How to containerize Golang app using Docker


To containerize a Golang app is similar to any other project. We need to use the base image for golandg and build the app.

Install Docker desktop , if you are on windows and create an account first. Then in the project create Dockerfile ( no extension required) with following command.

Save the file in root of the project

FROM  golang:1.18beta2-bullseye
RUN mkdir /app
ADD . /app
WORKDIR /app
RUN go build -o main .
CMD ["/app/main"]

Building the Docker Image

Go to the terminal and CD into the project folder and build the image. Docker image can be used to run different process.

docker build -t my-go-app . 

try to list image using docker images command.

Using the image

To use the image we created withrun command.

docker run -d -p 8080:8080 --name test1 my-go-app

The above command will run the image in detached mode, leaving console reedy for another execution.

It also exposed to port internal 8080:8080. Go to the browser and try localhost:8080 and it should have working.

Stopping, Starting and removing containers

Using docker stop <container-name/id>. Once it stopped can delete using docker rm container-name/id command.

Need to start again ? use the docker start command.

Wanna know running processes/ containers ? Try docker ps.

How to create API using mux in Golang

How to create simple API using golang and mux package


Golang is a programming language developed by Google. It can used to create cloud services, web , CLI tools etc. The first step to use Go is download and install the SDK.

Basic setup

To build basic API in Golang we need two packages

go get github.com/gorilla/mux

Mux help us to build API routes . In the main.go file add the following

package main

import  
("github.com/gorilla/mux"
"net/http"
"fmt")

// album represents data about a record album.
type album struct {
    ID     string  `json:"id"`
    Title  string  `json:"title"`
    Artist string  `json:"artist"`
    Price  float64 `json:"price"`
}

// albums slice to seed record album data.
var albums = []album{
    {ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
    {ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
    {ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}
  

func index(w http.ResponseWriter, r *http.Request){
 fmt.Fprint(w,"Hello world!")
}

func getAlbums(w http.ResponseWriter, r *http.Request){
 fmt.Fprint(w,albums)
}
func main(){
	r:=mux.NewRouter()
	r.HandleFunc("/",index).Methods("GET")
	r.HandleFunc("/albums",getAlbums)
	fmt.Println("Server starting")
	http.ListenAndServe(":8080",r)

	 }

Here we create a mux router instance which can be used to create API route. We also define handler function for the API too.

:= is the short hand in Golang for creating variables

Run the project

By using go run . or go run main.go can execute the program.

How to create API using gin in Golang

How to create simple API using golang and gin package


Golang is a programming language developed by Google. It can used to create cloud services, web , CLI tools etc. The first step to use Go is download and install the SDK.

Basic setup

To build basic API in Golang we need two packages

go get github.com/gin-gonic/gin

Gin help us to build API routes . In the main.go file add the following

package main

import  
("github.com/gin-gonic/gin"
"net/http")

  func index(c *gin.Context){
	c.JSON(200,gin.H{"message": "Welcome to Golang API"})
}

func main(){
	r:=gin.Default()
    r.GET("/",index)
	r.Run()
}

Here we create a gin instance which can be used to create API route. We also define handler function for the API too.

:= is the short hand in Golang for creating variables

Run the project

By using go run . or go run main.go can execute the program.

How to create API using Fiber in Golang

How to create simple API using golang and express like Fiber package


Golang is a programming language developed by Google. It can used to create cloud services, web , CLI tools etc. The first step to use Go is download and install the SDK.

Basic setup

To build basic API in Golang we need following packages

go get -u github.com/gofiber/fiber/v2

Fiber is express inspired library, if you were familiar with Nodejs express package, no worries . In the main.go file add the following

package main

import  
("github.com/gofiber/fiber/v2"
"fmt"
"log"
)
 
func api(c *fiber.Ctx) error {
    msg := fmt.Sprintf("✋ %s", c.Params("*"))
    return c.SendString(msg) // => ✋ register
}


func index(c *fiber.Ctx) error {
    return c.SendString("I am Fiber") // => ✋ register
}


func main(){
	app:= fiber.New()
    app.Get("/",index )
    app.Get("/api/*",api )
    log.Fatal(app.Listen(":3000"))
}

Here we create a Fiber router instance which can be used to create API route. We also define handler function for the API too.

:= is the short hand in Golang for creating variables

Run the project

By using go run . or go run main.go can execute the program.

Set up golang project

How to setup and use golang


Golang is a programming language developed by Google. It can used to create cloud services, web , CLI tools etc. The first step to use Go is download and install the SDK.

Hello world

After the installation please check the environment variables, make sure the path being added your system.

go version
go env

Now you are ready to stat writing your code. create a simple directory and cd into it.

on the terminal issue the following command to initialize the project module.

go mod init example/helloword 

It will create .mod file which is similar to package.json in Nodejs projects where dependencies listed.

create main.go

This is the entry point to your project. Every go program should start with a main function

//main.go
package main

import  "fmt"
func main(){
fmt.printline('Hello word')
}
 

Run the project

By using go run . or go run main.go can execute the program.

How to use GORM packages in Golang

How to use GORM package with SQLite database in Golang


Golang is a programming language developed by Google. It can used to create cloud services, web , CLI tools etc. The first step to use Go is download and install the SDK.

GORM

GORM is a ORM in Golang which help to generate and manipulate databases such as MySql, SQL server, SQLite etc. It will automatically create table for storing data based on ORM models.

In this example we are going to setup a SQLite database.

To make use of GORM first we need to add two packages

  • GORM
  • SQLITE drive

While using SQLite driver in Window there can be an gcc compiler error, please refer post link down below this post.

Let’s add the packages

 go get gorm.io/driver/sqlite
 gorm.io/driver/sqlite

Initialize and Migrate database with the ORM

First up all we need to generate a Model/Schema for our table and then initialize the database.

  type Product struct {
	gorm.Model
	Code  string
	Price uint
  }

With Automigrate GORM will make necessary changes in the database structure, only if there is a change occurs in the Schema.

	db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
	if err != nil {
	  panic("failed to connect database")
	}
	 // Migrate the schema
  db.AutoMigrate(&Product{})

The complete code for setup GORM is following.

Complete code
//main.go
package main

import (
	"fmt"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

  type Product struct {
	gorm.Model
	Code  string
	Price uint
  }

  func main() {
	db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
	if err != nil {
	  panic("failed to connect database")
	}

	 // Migrate the schema
  db.AutoMigrate(&Product{})
   // Create
  db.Create(&Product{Code: "D42", Price: 100})

   // Read
   var product Product
   db.First(&product, 1) // find product with integer primary key
   fmt.Println(product.Price)
    db.First(&product, "code = ?", "D42") // find product with code D42
 
  Update - update product's price to 200
    db.Model(&product).Update("Price", 200)
 db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // non-zero fields
 db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"})
 Delete - delete product
 db.Delete(&product, 1)
  }

How to solve gcc error in Golang -Windows

How to solve gcc compiler error in Golang on windows machine


On windows you may got the gcc compiler error while trying to add packages like “gorm.io/driver/sqlite” in Golang. The cause for the error is that, underlying package require the gcc C compiler which is not installed on Windows PC by default.

How to solve

We need to install the C compiler on Windows machine and also need to add the path to environment variable.

The easiest way to install the mingw package from tmd-gcc repository.

Also add the path to the bin folder as follows in environment variables.

C:\TDM-GCC-64\bin