0% found this document useful (0 votes)
3 views28 pages

GO 4 MODULE

The document provides an overview of the Go programming language and its standard library, highlighting various libraries and packages that facilitate application development. Key libraries discussed include GORM for database management, Gen for code generation, and Go Kit for microservices, among others. The document also covers essential concepts such as regular expressions, synchronization with the sync package, and struct definitions in Go.

Uploaded by

bagheera.gunnu18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views28 pages

GO 4 MODULE

The document provides an overview of the Go programming language and its standard library, highlighting various libraries and packages that facilitate application development. Key libraries discussed include GORM for database management, Gen for code generation, and Go Kit for microservices, among others. The document also covers essential concepts such as regular expressions, synchronization with the sync package, and struct definitions in Go.

Uploaded by

bagheera.gunnu18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

OVERVIEW OF STANDARD LIBRARY:

Go Language is a multi-purpose programming language. Developers build


fast, reliable and easy to build apps with Golang. Over the years from its
release, Go has become more stable and an easily adopted language with
strong community support, which expands to date.
Golang has fabulous documentation which actually narrows the scope which
relatively can be added in your project. Go is used for huge projects that can be
incorporated into massive large-scale distributed systems.

The Go standard library is a set of packages that contain pre-written


code to help you build applications at a faster rate. This course will
show you how to leverage these packages to handle input, read and
write files, create logs, and more

Today, we look into the best libraries and packages to make working with

Go even easier.

1. GORM
GORM is the most popular DB libraries for Go. It is a full-featured

object-relational mapping library for Golang. GORM is a developer-friendly

tool for converting data between incompatible type systems. It is specially

designed to minimize the rewritten codes when switching between type

systems. GORM provides SQL builders, RAW SQL, auto migration tools,

Extendable plugins for customization. All the features in GORM come with its

own tests so that developers can easily try something new without borking the

whole system.
2. Gen
Gen tool generates code for you. The tools help to generate type aware code in

particular which tries to alleviate the gap of lacking templates in Golang. With

no runtime magic, annotates your types with a special comment and generate

source files.

3. Goose
Managing the schema is the primary task when working on relational

databases. In some organizations, modifying the DB schema is considered a

daunting experience. Goose packages allow the developers to easily perform

schema changes and data migrations if required. It works by versioning the

schema, using migration files corresponding to each schema. The migrations

files can be SQL or Go commands.

4. cli
cli is a simple and fast package for building command-line apps for Golang. It

allows the developers to develop their own expressive command-line apps. cli

is used for creating flags, bash-completion routines and generates help texts.

cli is fast, fun and playful when you code for an API.
5. Go Kit
Go Kit is GitHub’s most popular standard library for Go related Microservice.

This library offers specialized support for microservices. Go kit addresses the

gap between functions such as RPC safety, infrastructure integration, system

observability, and program design. It also provides guidance for building

distributed systems with a solution to common problems.

6. Vegeta
Vegeta is a tool used for HTTP load testing. This versatile tool was specially

designed for testing HTTP services with a constant request rate. It works

efficiently on analyzing the weak points of the program. Vegeta is one of the

libraries that work throughout to improve the overall performance. It is

presumably named after the Saiyan prince for its attack both targeted and

distributed functions as a load tester.

7. Authboss
Authboss is a library for Go and also a modular web authentication system.

This is an effective time-saver, it has several common authentication and

authorization modules left for the developer’s choice. It is an easy way to

integrate it, even without web frameworks and use it for fixing the bugs.
8. Glide
Glide is a package manager for Go. Glides offer help to manage each program

in its own vendor directory of package dependencies. It comes with the

support of aliasing packages, versioning packages, support for custom

local-global plugins, and easily manages and install-on-demand dependencies,

resolves version differences and works with more tools.

Also Read

8 Best IDEs For Developing In Golang

9. Ginkgo
Ginkgo is a Behaviour Driven Development (BDD) testing framework. It

allows you to write your tests in a syntax that resembles the English language,

which makes it easy for people with less or no technical knowledge to review

the tests or outputs which match the requirements of the business. It has a

stylish test specification to integrate with Go’s inbuilt testing package and is

often combined with Gomega.

10. Docker
Docker is a service product that is used for OS-level virtualization to deliver

software in packages called containers. As it comes from the DevOps family

most of the developers are not aware that Docker is implemented in Go.

Docker is used in significant projects and becoming popular for Go projects.

11. Kubernetes
Kubernetes is an open-source container orchestration platform for

cloud-native applications. It is a distributed system implemented in Go.

Kubernetes is flexible and comes with extendable and customizable plugins for

use.

12. Fuzzy
Fuzzy is a dependency-free Go library, it is used to match fuzzy strings. It is

optimized for file names and code symbols. It provides speed and intuitive

matching within milliseconds. Fuzzy determines quality matches according to

its own internal logic. Fuzzy is Unicode aware and can parse IntelliJ IDEA,

VScode, SublimeText and more.

13. mgo
mgo is a library for Golang. It is a MongoDB driver that implements rich

functionalities under a simple API standard for Go idioms. With mgo, you get
superior performance with Flexible serialization. It has the support of GridFS

and Failover managements. Another main advantage, it is fast and actively

maintained with authentication support for pooling integration.

14. NSQ
NSQ is a robust distributed queue. It is primarily used for a building block for

large scale distributed systems. It is a simple TCP protocol that supports client

libraries in any language. It is a combination of load-balanced and multicast

style message routing. There are few dependencies that are easy to deploy with

the default configuration. There is no need for the client library to publish the

HTTP interface for stats.

15. Etcd
Etcd is a reliable distributed key-Value store. It is a simple, well defines

user-facing API. The server can be easily implemented and the Goe client

interacts with it through gRPC. It is highly secure with automatic TLS with

authentication, Fast and reliable with properly distributed using Raft.

the regexp package


A Regular Expression (or RegEx) is a special sequence of characters that

defines a search pattern that is used for matching specific text. In Golang,

there’s a built-in package for regular expressions, called the regexp package

which contains all list of actions like filtering, replacing, validating, or

extracting. It uses the RE2 syntax standards. The MatchString() function

reports whether the string passed as a parameter contains any match of the

regular expression pattern.

Syntax:

func MatchString(pattern string, s string)

Returns: matched bool, err error

// Golang program to illustrate the

// string matching using regexp

// in-built function

package main

import (
​ "fmt"

​ "regexp"

func main() {

​ // string in which the pattern

​ // is to be found

​ str := "geeksforgeeks"

​ // returns true if the pattern is present

​ // in the string, else returns false

​ // err is nil if the regexp is valid


​ match1, err := regexp.MatchString("geeks", str)

​ fmt.Println("Match: ", match1, " Error: ", err)

​ // this returns false as the match

​ // is unsuccessful

​ str2 := "ComputerScience"

​ match2, err := regexp.MatchString("geeks", str2)

​ fmt.Println("Match: ", match2, "Error: ", err)

​ // this will throw an error

​ // as the pattern is not valid

​ match3, err := regexp.MatchString("geek(s", str2)

​ fmt.Println("Match: ", match3, "Error: ", err)


}

OUTPUT:

Match: true Error: <nil>

Match: false Error: <nil>

Match: false Error: error parsing regexp: missing closing ):

`geek(s

https://www.geeksforgeeks.org/what-is-regex-in-golang/

locking and the sync package,

The `sync` package in Go provides synchronization primitives for concurrent

programming. The `sync.Mutex` type is used to create locks for mutual

exclusion, allowing only one goroutine to access a shared resource at a time.

The `Lock()` method acquires the lock, and the `Unlock()` method releases it.

Using a mutex helps prevent race conditions and ensures the correctness of

shared resources. Other synchronization primitives in the `sync` package

include `sync.RWMutex`, `sync.Cond`, and `sync.WaitGroup`.

package main
import (

​ "fmt"

​ "sync"

​ "time"

var (

​ counter = 0

​ mutex sync.Mutex

func increment() {

​ mutex.Lock() // Acquire the lock

​ defer mutex.Unlock() // Release the lock when the function returns


​ counter++

func main() {

​ // Launch multiple goroutines to concurrently increment the counter

​ for i := 0; i < 10; i++ {

​ ​ go increment()

​ }

​ // Wait for all goroutines to finish

​ time.Sleep(time.Second)

​ fmt.Println("Counter:", counter)
}

custom packages and visibility:

https://www.digitalocean.com/community/tutorials/understandin

g-package-visibility-in-go

using godoc for your custom packages

The Go project takes documentation seriously. Documentation is a huge

part of making software accessible and maintainable. Of course it must

be well-written and accurate, but it also must be easy to write and to

maintain. Ideally, it should be coupled to the code itself so the

documentation evolves along with the code. The easier it is for

programmers to produce good documentation, the better for everyone.

To that end, we have developed the godoc documentation tool. This

article describes godoc’s approach to documentation, and explains how


you can use our conventions and tools to write good documentation for

your own projects.

Godoc parses Go source code - including comments - and produces

documentation as HTML or plain text. The end result is documentation

tightly coupled with the code it documents. For example, through

godoc’s web interface you can navigate from a function’s documentation

to its implementation with one click.

Godoc is conceptually related to Python’s Docstring and Java’s Javadoc

but its design is simpler. The comments read by godoc are not language

constructs (as with Docstring) nor must they have their own

machine-readable syntax (as with Javadoc). Godoc comments are just

good comments, the sort you would want to read even if godoc didn’t

exist.

The convention is simple: to document a type, variable, constant,

function, or even a package, write a regular comment directly preceding

its declaration, with no intervening blank line. Godoc will then present

that comment as text alongside the item it documents. For example, this

is the documentation for the fmt package’s Fprint function:

// Fprint formats using the default formats for its operands and writes to

w.

// Spaces are added between operands when neither is a string.


// It returns the number of bytes written and any write error encountered.

func Fprint(w io.Writer, a ...interface{}) (n int, err error) {

Notice this comment is a complete sentence that begins with the name

of the element it describes. This important convention allows us to

generate documentation in a variety of formats, from plain text to HTML

to UNIX man pages, and makes it read better when tools truncate it for

brevity, such as when they extract the first line or sentence.

Comments on package declarations should provide general package

documentation. These comments can be short, like the sort package’s

brief description:

// Package sort provides primitives for sorting slices and user-defined

// collections.

package sort

They can also be detailed like the gob package’s overview. That package

uses another convention for packages that need large amounts of


introductory documentation: the package comment is placed in its own

file, doc.go, which contains only those comments and a package clause.

When writing a package comment of any size, keep in mind that its first

sentence will appear in godoc’s package list.

Comments that are not adjacent to a top-level declaration are omitted

from godoc’s output, with one notable exception. Top-level comments

that begin with the word "BUG(who)” are recognized as known bugs,

and included in the “Bugs” section of the package documentation. The

“who” part should be the user name of someone who could provide

more information. For example, this is a known issue from the bytes

package:

// BUG(r): The rule Title uses for word boundaries does not handle

Unicode punctuation properly.

Sometimes a struct field, function, type, or even a whole package

becomes redundant or unnecessary, but must be kept for compatibility

with existing programs. To signal that an identifier should not be used,

add a paragraph to its doc comment that begins with “Deprecated:”

followed by some information about the deprecation.


There are a few formatting rules that Godoc uses when converting

comments to HTML:

●​ Subsequent lines of text are considered part of the same

paragraph; you must leave a blank line to separate paragraphs.

●​ Pre-formatted text must be indented relative to the surrounding

comment text (see gob’s doc.go for an example).

●​ URLs will be converted to HTML links; no special markup is

necessary.

Note that none of these rules requires you to do anything out of the

ordinary.

In fact, the best thing about godoc’s minimal approach is how easy it is

to use. As a result, a lot of Go code, including all of the standard library,

already follows the conventions.

Structs

Definition of a struct:
A structure or struct in Golang is a user-defined type that allows to

group/combine items of possibly different types into a single type. Any

real-world entity which has some set of properties/fields can be represented

as a struct. This concept is generally compared with the classes in

object-oriented programming. It can be termed as a lightweight class that

does not support inheritance but supports composition. For Example, an

address has a name, street, city, state, Pincode. It makes sense to group

these three properties into a single structure address as shown below.

Declaring a structure:

type Address struct {

name string

street string

city string

state string

Pincode int

}
In the above, the type keyword introduces a new type. It is followed by the

name of the type (Address) and the keyword struct to illustrate that we’re

defining a struct. The struct contains a list of various fields inside the curly

braces. Each field has a name and a type.

Note: We can also make them compact by combining the various fields of the

same type as shown in the below example:

type Address struct {

name, street, city, state string

Pincode int

To Define a structure: The syntax for declaring a structure:

var a Address

The above code creates a variable of a type Address which is by default set

to zero. For a struct, zero means all the fields are set to their corresponding

zero value. So the fields name, street, city, state are set to “”, and Pincode is

set to 0. You can also initialize a variable of a struct type using a struct literal

as shown below:
var a = Address{"Akshay", "PremNagar", "Dehradun",

"Uttarakhand", 252636}

Note:

●​ Always pass the field values in the same order in which they are

declared in the struct. Also, you can’t initialize only a subset of fields

with the above syntax.

●​ Go also supports the name: value syntax for initializing a struct (the

order of fields is irrelevant when using this syntax). And this allows

you to initialize only a subset of fields. All the uninitialized fields are

set to their corresponding zero value. Example:

var a = Address{Name:”Akshay”, street:”PremNagar”, state:”Uttarakhand”,

Pincode:252636} //city:””

// Golang program to show how to

// declare and define the struct

package main
import "fmt"

// Defining a struct type

type Address struct {

​ Name string

​ city string

​ Pincode int

func main() {

​ // Declaring a variable of a `struct` type

​ // All the struct fields are initialized

​ // with their zero value

​ var a Address

​ fmt.Println(a)
​ // Declaring and initializing a

​ // struct using a struct literal

​ a1 := Address{"Akshay", "Dehradun", 3623572}

​ fmt.Println("Address1: ", a1)

​ // Naming fields while

​ // initializing a struct

​ a2 := Address{Name: "Anikaa", city: "Ballia",

​ ​ ​ ​ ​ ​ ​ ​ Pincode: 277001}

​ fmt.Println("Address2: ", a2)

​ // Uninitialized fields are set to


​ // their corresponding zero-value

​ a3 := Address{Name: "Delhi"}

​ fmt.Println("Address3: ", a3)

How to access fields of a struct?

To access individual fields of a struct you have to use dot (.) operator.

Ex:

// Golang program to show how to

// access the fields of struct

package main

import "fmt"

// defining the struct

type Car struct {

​ Name, Model, Color string


​ WeightInKg​ ​ float64

// Main Function

func main() {

​ c := Car{Name: "Ferrari", Model: "GTC4",

​ ​ ​ Color: "Red", WeightInKg: 1920}

​ // Accessing struct fields

​ // using the dot operator

​ fmt.Println("Car Name: ", c.Name)

​ fmt.Println("Car Color: ", c.Color)

​ // Assigning a new value

​ // to a struct field

​ c.Color = "Black"


​ // Displaying the result

​ fmt.Println("Car: ", c)

Output:

Car Name: Ferrari

Car Color: Red

Car: {Ferrari GTC4 Black 1920}

Creating a struct variable with a factory method:

https://refactoring.guru/design-patterns/factory-method/go/example

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"`

Other Go code is then capable of examining these structs and extracting the
values assigned to specific keys it requests. Struct tags have no effect on the
operation of your code without additional code that examines them.

Try this example to see what struct tags look like, and that without code from
another package, they will have no effect.

package main

import "fmt"

type User struct {

​ Name string `example:"name"`

func (u *User) String() string {


​ return fmt.Sprintf("Hi! My name is %s", u.Name)

func main() {

​ u := &User{

​ ​ Name: "Sammy",

​ fmt.Println(u)

Output

Hi! My name is Sammy

You might also like