Full Stack
Full Stack
Developer Guide
Guidelines to become a full stack
developer
Prepared By
W3 ENGINEERS LTD
Contents
......................................................................................................................................................... 0
Introduction .................................................................................................................................... 4
About W3 .................................................................................................................................... 4
Product and Services .................................................................................................................. 4
Our Products ........................................................................................................................... 4
Our Services............................................................................................................................. 5
Our Values................................................................................................................................... 5
Core Values .............................................................................................................................. 6
Success Stories ......................................................................................................................... 6
Our Team ................................................................................................................................. 7
Work Culture ........................................................................................................................... 7
Training and Development of Intern: ............................................................................................. 8
About Office etiquette, Organization, and office norms ............................................................ 8
Programmers ............................................................................................................................. 10
Mistakes .................................................................................................................................... 10
Productivity ............................................................................................................................... 10
Coding........................................................................................................................................ 11
Web Architecture .......................................................................................................................... 13
The diagram............................................................................................................................... 14
How WWW [Web Addresses] Translates .................................................................................. 15
Monoliths .................................................................................................................................. 15
Overview ................................................................................................................................ 15
Benefits .................................................................................................................................. 16
Drawbacks ............................................................................................................................. 16
Microservices ............................................................................................................................ 17
Overview ................................................................................................................................ 17
Benefits .................................................................................................................................. 17
Drawbacks ............................................................................................................................. 18
Conclusion ............................................................................................................................. 19
Micro frontends ........................................................................................................................ 19
Quick Summary...................................................................................................................... 19
What is Micro-frontend Architecture? .................................................................................. 20
Benefits .................................................................................................................................. 20
Drawbacks ............................................................................................................................. 20
How it works? ........................................................................................................................ 21
Programming languages ............................................................................................................... 21
Frontends .................................................................................................................................. 21
HTML & CSS for responsive web ........................................................................................... 21
HTML5 Basic overview .............................................................................................................. 21
CSS3 Basic overview ............................................................................................................... 23
JavaScript core ....................................................................................................................... 45
NodeJs.................................................................................................................................... 57
Reactive framework............................................................................................................... 69
Backends ................................................................................................................................... 79
RDBMS & No SQL ................................................................................................................... 79
Python.................................................................................................................................... 85
Generative AI and LLM ........................................................................................................ 110
Golang .................................................................................................................................. 110
Cloud Infrastructure.................................................................................................................... 125
Deployment tools and techniques .......................................................................................... 125
Cloud Infrastructure ................................................................................................................ 125
Amazon Web Service (AWS).................................................................................................... 125
EC2 ....................................................................................................................................... 125
VPC ....................................................................................................................................... 126
S3 ......................................................................................................................................... 126
CloudFront ........................................................................................................................... 126
RDS ....................................................................................................................................... 127
NoSQL .................................................................................................................................. 127
Route53 ............................................................................................................................... 128
SQS ....................................................................................................................................... 128
Elastic Beanstalk .................................................................................................................. 128
Elasticsearch ........................................................................................................................ 129
Lambda ................................................................................................................................ 129
CloudFormation ................................................................................................................... 130
Linux (OS) ................................................................................................................................ 130
Docker ..................................................................................................................................... 131
Docker Compose .................................................................................................................. 132
GIT ........................................................................................................................................... 133
IDE ........................................................................................................................................... 134
Automation Tools .................................................................................................................... 134
Introduction
About W3
W3 Engineers Ltd is a fast-paced IT solutions provider that specializes in delivering innovative
solutions and strategies that drive business growth.
Established in 2009, W3 Engineers Ltd has been providing top-tier custom software development,
innovative software products, and cost-effective technical services.
With over a decade of experience in providing technology services, quality software products,
and offshore team management to clients worldwide, we have established a reputation for
excellence in the industry.
Our Values
Our team thrives on a set of core values that guide us in everything we do. Honesty, integrity,
health and well-being, personal growth, and social responsibility are at the forefront of our
mission. We embrace creativity, innovation, empathy, and compassion in all our actions. And
never forget to appreciate the opportunities and blessings we've been given. Together, these
values allow us to positively impact our community and prioritize the well-being of our families
while continuously growing and learning from our actions and mistakes.
Vision: We strive for technological breakthroughs which will impact human life positively, that's
our vision.
Mission: To cultivate customer relations by providing the best services and solutions at the most
affordable costs.
Core Values
Success Stories
Our Team
Work Culture
If you need to leave the office premises, kindly notify your supervisor and the HR
department. Ensure to obtain the final confirmation of departure from the HR
department before leaving, as no employee can exit the office without securing this
confirmation.
All leave requests (Emergency leaves/Planned leaves) should be submitted to the team
lead. Planned leave should be requested at least 7 days earlier to the date of leave and
for emergency leave, employees are bound to notify it before 10:00 AM (on that day).
Neglecting to communicate your absence on a given day will be considered an "Absent"
status, irrespective of the availability of paid leave entitlements.
Throughout the internship/probation period, both interns and probation period
employees will not have access to paid leave benefits.
If you experience an emergency resulting in a late arrival or early departure, please
promptly inform your Lead, PM, and HR to facilitate necessary coordination.
We have designated lunch break (2:00 PM to 3:00 PM). Our schedule does not include
extended breaks. For prayer sessions and snacks, employees have the flexibility to take
short breaks (Max 15 mins) as needed.
Programmers
"[Programmers] like to think we spend most of our time power typing. “Yeah, I’m being
productive, I’m writing programs!” But we don’t. We spend most of our time looking into the
abyss, saying “My God, what have I done? How am I ever going to make this work?” Once we
figure it out, we forget that we did all of that … A normal person, once they’ve looked into the
abyss, would say I’m done, this is stupid, I’m going to do something else. But not us, because
there’s something wrong with us.” - Douglas Crockford
Mistakes
Spell mistakes
Naming things incorrectly
Incorrect file names. E.g., OS dependent
Over abstraction. E.g. Over thinking of product
Messy inheritance. E.g. Vehicle / boat, airplane
Syntax error. E.g. Not testing or overlook
Permissions error. E.g. test, development or production mess up
Memory Hungry Loop. E.g. large datasets?
Incorrect operators. E.g. >/>=?, &/and?, brackets
Self-doubt
Productivity
Hot keys, even in browsers
Multiple screen/Large Screen
Proper development environment
Real time notes and to-do app. E.g. Wunderlist, Evernote/OneNote
Refactor code. E.g. Think to make it more efficient
Read/Follow open-source codes
Automate as much as possible
Read books
Re-useable codes, don’t re-invent the wheel rather learn to use
Coding
Prevention is better than the cure!
o My code my responsibility
o For every professional there are some basic rules. E.g.
o Doctor wear aprons
o Accountants have a calculator
o Chefs wears toque
o Easy to understand + Easy to change
o Write codes that expresses
o Don’t overload names or concepts. E.g.
o Same things on multiple names/functions.
o Redundant layers
o No meaningful names
o Careful yourself with dependencies. E.g.
o Singular direction.
o Update will be complex if not.
o Organization forever! E.g.
o Unusable file not to keep
o Redundant directory structure or files should avoid
o Learn and modify to improve
o Commenting
o Don’t make it to tell lies
o Don’t use unless it requires
o But don’t miss it
o Boy Scout rules
o Leave the code to a better way than you found
o Single work principle
o One function do one thing. E.g.
o If we have more argument onto a function possibly it can do multiple things.
o So, it can hard to debug or verify
o Tests
o Integration test
o Unit test
o Development Strategy
o Work in short cycle
o Incremental and Iterative
Web Architecture
The diagram
How WWW [Web Addresses] Translates
Monoliths
Overview
Monolith means composed all in one piece. The Monolithic application describes a single-
tiered software application in which different components combined into a single program
from a single platform. Components can be:
- Authorization
- Presentation
- Business Logic
- Database Layer
- Integrations
Figure: Monolithic Architecture (for E-Commerce Application)
Benefits
Simple to develop — At the beginning of a project it is much easier to go with
Monolithic Architecture.
Simple to test. For example, you can implement end-to-end testing by simply launching
the application and testing the UI with Selenium.
Simple to deploy. You have to copy the packaged application to a server.
Simple to scale horizontally by running multiple copies behind a load balancer.
Drawbacks
Maintenance — If Application is too large and complex to understand entirely, it is
challenging to make changes fast and correctly.
The size of the application can slow down the start-up time.
You must redeploy the entire application on each update.
Monolithic applications can also be challenging to scale when different modules have
conflicting resource requirements.
Reliability — Bug in any module (e.g. memory leak) can potentially bring down the
entire process. Moreover, since all instances of the application are identical, that bug
impact the availability of the entire application
Regardless of how easy the initial stages may seem; Monolithic applications have
difficulty to adopting new and advance technologies. Since changes in languages or
frameworks affect an entire application, it requires efforts to thoroughly work with the
app details, hence it is costly considering both time and efforts.
Microservices
Overview
Microservices are an approach to application development in which a large application is built
as a suite of modular services (i.e. loosely coupled modules/components). Each module
supports a specific business goal and uses a simple, well-defined interface to communicate with
other sets of services.
Instead of sharing a single database as in Monolithic application, each microservice has its own
database. Having a database per service is essential if you want to benefit from microservices,
because it ensures loose coupling. Each of the services has its own database. Moreover, a
service can use a type of database that is best suited to its needs.
Micro frontends
Quick Summary
The micro-frontend architecture has slowly but gradually gained popularity and has now
become one of the most sought-after frontend development strategies. Developers appreciate
the agility and freedom that comes along with this architecture and organizational stability it
imparts is making life easier for CTOs worldwide. With multiple implementation strategies and
tons of advantages, the micro-frontend architecture seems set to revolutionize frontend
development and scaling.
What is Micro-frontend Architecture?
Micro-frontend architecture is a strategy in which the traditionally monolithic frontend
codebase is split into smaller apps, ideally addressing the various business domains. All these
smaller elements form a seamless frontend interface that delivers top-notch user experience
and is easy to modify and scale.
Benefits
- Design and development flexibility
- Decoupled codebases
- Automation
- Fault isolation
- Scalability
- Faster build time
- Simpler maintenance
- Independent Deployment
- Autonomous team
- Reusability
Drawbacks
- Operational complexities
- Inconsistent user experience
- Poor communication between components
- Larger payloads
How it works?
Programming languages
Frontends
HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and
XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web.
HTML5 is a cooperation between the World Wide Web Consortium (W3C) and the Web Hypertext
Application Technology Working Group (WHATWG).
The new standard incorporates features like video playback and drag-and-drop that have been
previously dependent on third-party browser plug-ins such as Adobe Flash, Microsoft Silverlight,
and Google Gears.
HTML5 Tags
The following section contains a complete list of standard tags belonging to the latest HTML5 and
XHTML 1.1 specifications. All the tags are listed alphabetically.
Ref: https://www.tutorialrepublic.com/html-reference/html5-tags.php
CSS (Cascading Style Sheets) consist of a group of formatting rules that you use to control the
layout and appearance of the content on a web page. One really great feature of CSS is that you
can store all the CSS rules in one document and keep that document separate from the HTML
content and link the two together. Then, when you make a change to the CSS that change is
instantly and automatically updated on all the HTML files. Another great feature is that it
“cleans up” the appearance of the code on web pages. In addition, it will speed up browser
loading times.
What CSS gives you is incredible control over the appearance of your page. You can control
properties such as font sizes, bolding, italics, text shadows and color, link color and much more.
And of course, you can go far beyond that with page layout tools, boxes, formatting,
positioning, etc. In CSS3, there are many options, a few which we’ll look at here. These include
animation, gradients, media queries, shadows, transitions, the font-face rule that allows you to
embed fonts on a web page, and more.
CSS Save Lots of Time — CSS gives lots of flexibility to set the style properties of an
element. You can write CSS once; and then the same code can be applied to the groups
of HTML elements, and can also be reused in multiple HTML pages.
Easy Maintenance — CSS provides an easy means to update the formatting of the
documents, and to maintain the consistency across multiple documents. Because the
content of the entire set of web pages can be easily controlled using one or more style
sheets.
Pages Load Faster — CSS enables multiple pages to share the formatting information,
which reduces complexity and repetition in the structural contents of the documents. It
significantly reduces the file transfer size, which results in a faster page loading.
Superior Styles to HTML — CSS has much wider presentation capabilities than HTML
and provide much better control over the layout of your web pages. So you can give far
better look to your web pages in comparison to the HTML presentational elements and
attributes.
Multiple Device Compatibility — CSS also allows web pages to be optimized for more
than one type of device or media. Using CSS the same HTML document can be
presented in different viewing styles for different rendering devices such as desktop, cell
phones, etc.
Ref : https://www.tutorialrepublic.com/css-tutorial/css-get-started.php
What is Stylus?
Stylus is a dynamic stylesheet preprocessor language that is compiled into Cascading Style
Sheets (CSS). Its design is influenced by Sass and LESS. It's regarded as the fourth most used CSS
preprocessor syntax. It was created by TJ Holowaychuk, a former programmer for Node
CSS in itself is devoid of complex logic and functionality which is required to write reusable and
organized code. As a result, a developer is bound by limitations and would face extreme
difficulty in code maintenance and scalability, especially when working on large projects
involving extensive code and multiple CSS stylesheets. This is where CSS Preprocessors come to
the rescue.
A CSS Preprocessor is a tool used to extend the basic functionality of default vanilla CSS through
its own scripting language. It helps us to use complex logical syntax like – variables, functions,
mixins, code nesting, and inheritance to name a few, supercharging your vanilla CSS. By using
CSS Preprocessors, you can seamlessly automate menial tasks, build reusable code snippets,
avoid code repetition and bloating and write nested code blocks that are well organized and
easy to read.
However, browsers can only understand native vanilla CSS code and will be unable to interpret
the CSS Preprocessor syntax. Therefore, the complex and advanced Preprocessor syntax needs
to be first compiled into native CSS syntax which can then be interpreted by the browsers to
avoid cross browser compatibility issues. While different Preprocessors have their own unique
syntaxes, eventually all of them are compiled to the same native CSS code.
Moving forward in the article, we will take a look at the 3 most popular CSS Preprocessors
currently being used by developers around the world i.e Sass, LESS, and Stylus.
 
COMPILED CSS
In both cases, be it Sass or SCSS, the compiled CSS code will be the same –
Syntax Declaration: Stylus
Uses .styl extension. Stylus offers a great deal of flexibility in writing syntax, supports native CSS
as well as allows omission of brackets colons and semicolons. Also, note that Stylus does not
use @ or $ symbols for defining variables. Instead, Stylus uses the assignment operators to
indicate a variable declaration.
Stylus
COMPILED CSS
I
More Information:
SASS docs: http://sass-lang.com/
Stylus docs: http://stylus-lang.com/
CSS Flexbox: A Complete Guide
This guide explains everything about flexbox, focusing on different properties for the flex
container (the parent element) and the flex items (the child elements). It includes various
examples and lifehacks.
CSS flexbox (Flexible Box Layout Module) is a layout module that consists of the flex container
(the parent element) and the flex items (the children elements). The flex items can be
organized as a row or as a column, and the available free space can be distributed between
them in various ways.
With the help of flexbox, you can:
Automatically scale elements (alter height or width) so that they fill the available space
Automatically shrink or grow elements to make them fit into the container and prevent
overflow
And more
Flexbox elements can have many properties some of which are set on the flex container and
the others are set on the flex items.
Properties that apply to the flex container:
align-content
align-items
display
flex-direction
flex-flow
flex-wrap
justify-content
flex-basis
flex-grow
flex-shrink
order
How to Create the Flex Container
The display: flex; property applies to the container, makes the container a block element,
and enables the flex layout for all its direct children.
The display: inline-flex; works in the same way. Only it creates a container as an inline
element.
How to Create a Row or Column
If you want to arrange the flex items to look like a row or a column, apply the flex-
direction property to the container.
The flex-direction: row; property will make a horizontal row. The row is the default
value.
If you have more items that can fit in one row and you still want a horizontal layout, the flex-
wrap: wrap; property will come in handy. This way, the flex items will wrap onto multiple
lines inside the flex container. The default value is flex-wrap: nowrap;.
To make a vertical column, apply the flex-direction: column; to the container.
How to Align Elements Horizontally
To define the horizontal alignment of items, use the justify-content property. It may have
one of the following values:
flex-start: items are packed toward the container’s left side (it’s the default value)
flex-end: items are packed toward the container’s right side
space-between: items are evenly distributed in the line (the first item is on the left, the
last item on the right)
space-around: items are evenly distributed in the line with equal space on both sides of
the items. Note that visually the spaces aren’t equal since all the items have equal space
on both sides. The margins of adjacent flex items do not collapse. The first item will
have one unit of space against the container edge, but two units of space between the
next item because that next item has its own spacing that applies
space-evenly: items are distributed so that the spacing between any two items (and the
space to the edges) is equal
How to Align Elements Vertically
To align flex items vertically, use the align-items, align-content or align-self
properties.
Align-items
To define the vertical alignment of several items, apply the align-items property to the
container. This property may have one of the following values:
stretch: items are stretched to fill the container, still respecting min-width and max-
width properties (it’s the default value)
flex-start: items are placed in the top part of the container
In other words, there must be additional vertical space inside the container, which should be
larger than the sum of all the heights of the rows of elements.
This property may have one of the following values:
stretch: lines stretch to take up all the available space in the container (it’s the default
value)
flex-start: lines are placed in the top part of the container
space-around: lines are evenly distributed with equal space around each line
Align-self
To vertically align individual items, use the align-self property. It applies to the flex items,
not to the flex container. It is useful to override the alignment specified for the flex container
with the help of the align-items property.
The align-self property may have one of the following values (the same ones as in the case
of the align-items property plus auto):
auto: equals to the value specified in the align-items property for the flex container
(it’s the default value)
stretch: items are stretched to fill the container, still respecting min-width and max-
width properties
To arrange flex items in a column bottom to top, use the flex-direction: column-
reverse; property.
Instead of flex-direction, you can choose the shorter flex-flow property to apply those
values:
Wrap-reverse
There is also the flex-wrap: wrap-reverse; property that allows wrapping flex items onto
multiple lines from bottom to top.
How to Make the Elements Grow or Shrink
The flexibility of flex items is determined by the flex-basis, flex-grow, and flex-shrink
properties.
Flex-basis
The flex-basis property defines the default size of the flex item before the available space is
distributed. You can set an absolute value (e. g. 200px or 10em), a percentage value (e. g. 50%)
or a keyword (auto, content).
The flex-basis property can be interpreted as the minimum width of the flex item. If you
specify a flex-basis value, it will set the width for the specific item, but depending on other
flex parameters the flex item may become wider (or narrower) than the flex-basis value.
The default value is auto. It retrieves the value of the width property. And the content value is
based on the flex item’s content.
If you do not set a flex-basis value and set the flex-grow value to 0, the element will be
compressed to its minimum size.
Flex-grow
The flex-grow property applies to individual flex items and defines the ability of a flex item to
grow. It dictates what amount of the available space inside the flex container the item should
take up. It accepts a unitless value that serves as a proportion. The default value is 0. Negative
numbers are invalid.
If all items have flex-grow set to 1, the remaining space in the container will be distributed
equally to all children. If the flex-grow value of an item is set to 2, it will get 2 times more pixels
to the original width than other items with the flex-grow value 1.
Flex-shrink
The flex-shrink property applies to the flex items and indicates how much each
element will be reduced if there is not enough available space. It accepts a unitless value
that serves as a proportion. The default value is 1. The value 0 allows keeping the item’s
original size. Negative numbers are invalid.
The idea of responsive design is that the product can adapt itself to any reading device the user may use. It’s
more or less like transforming the content into water, mimicking the liquid’s ability to fill any type of glass. This
shows that the old way of creating websites, using fixed positions, is all but dead and buried.
Web pages can be viewed using many different devices. Your web page should look good and needs to be
interactive, regardless of the device. When you use CSS to resize, hide, shrink and enlarge content to make it look
better, it is called CSS Responsive Design. CSS Responsive Design responds to the needs of the users and the
devices they are using. The layout changes based on the size and capabilities of the device. CSS Responsive Design
ensure that web pages don't leave out information to fit smaller devices, but rather adapt its content to fit any
device such as Desktop, Tablet or Phone.
Single breakpoint
@media (min-width: 768px) and (max-width: 991.98px) { ... }
Max-width
// X-Small devices (portrait phones, less than 576px)
@media (max-width: 575.98px) { ... }
// Small devices (landscape phones, less than 768px)
@media (max-width: 767.98px) { ... }
// Medium devices (tablets, less than 992px)
@media (max-width: 991.98px) { ... }
// Large devices (desktops, less than 1200px)
@media (max-width: 1199.98px) { ... }
// X-Large devices (large desktops, less than 1400px)
@media (max-width: 1399.98px) { ... }
JavaScript core
Introduction
JavaScript is the world's most popular programming language.
JavaScript is the mother language of the Web.
JavaScript is easy to learn.
JavaScript is one of the 3 languages all web developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages
JS Functions
JavaScript functions are defined with the function keyword.
Self-Invoking Functions
For function parameters:
Arguments are Passed by Value
Objects are Passed by Reference
JS HTML DOM
With the HTML DOM, JavaScript can access and change all the elements of an HTML document.
The HTML DOM model is constructed as a tree of Objects:
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
JS Browser BOM
The window object is supported by all browsers. It represents the browser's window.
All global JavaScript objects, functions, and variables automatically become members of the
window object.
Global variables are properties of the window object.
Global functions are methods of the window object.
Even the document object (of the HTML DOM) is a property of the window object:
window.document.getElementById("header");
is the same as:
document.getElementById("header");
Promise
A Promise in JavaScript is an object that represents the eventual completion (or failure) of an
asynchronous operation and its resulting value. A Promise has three main states:
1. Pending: Initial state, neither fulfilled nor rejected.
2. Fulfilled: Operation completed successfully, resulting in a resolved value.
3. Rejected: Operation failed, resulting in a reason for the failure.
if (success) {
resolve("Data fetched successfully!"); // fulfills the promise
} else {
reject("Failed to fetch data."); // rejects the promise
}
}, 1000);
});
1. Creating a Promise:
The new Promise constructor takes a function with two parameters: resolve (for
success) and reject (for failure).
When the operation is successful, we call resolve(), passing the result. This
moves the promise to the fulfilled state.
3. Rejecting the Promise:
If the operation fails, reject() is called with an error message, moving the
promise to the rejected state.
In this example, if success is true, the promise is resolved, and "Data fetched successfully!" is
logged. If success is false, the promise is rejected, and "Failed to fetch data." is logged as an
error.
JS Ajax
AJAX (Asynchronous JavaScript and XML) is a developer's dream, because you can:
Read data from a web server - after the page has loaded
Update a web page without reloading the page
Send data to a web server - in the background
Fetch
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' +
response.statusText);
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There has been a problem with your fetch
operation:', error);
});
Explanation
1. fetch('https://api.example.com/data'): Initiates a request to the given URL. fetch
returns a Promise that resolves to the Response object representing the response to the
request.
2. then(response => { ... }): Processes the response. Here:
• We check if the response status is “ok” (i.e., status code is 200–299).
• If it’s not, we throw an error with response.statusText for debugging.
• If the response is ok, we call response.json() to parse the JSON data.
3. then(data => { ... }): The parsed JSON data is now accessible. Here, we simply log
it with console.log(data).
4. catch(error => { ... }): Catches any error during the fetch process or response
handling. If there’s a network error or if the fetch promise rejects, we log an error message.
JSON
JSON stands for JavaScript Object Notation
JSON is a text format for storing and transporting data
JSON is "self-describing" and easy to understand
name
age
car
Each property has a value.
Use the JavaScript function JSON.parse() to convert text into a JavaScript object:
Is similar to
Use the JavaScript function JSON.stringify() to convert it into a string.
When a user visits a web page, his/her name can be stored in a cookie.
Next time the user visits the page, the cookie "remembers" his/her name.
More storages are localStorage, sessionStorage.
We can set cookie expiry but localStorage does not have any expiry.
sessionStorage gets cleared when browser closed.
localStorage and sessionStorage did not pass to header on page visits like cookie.
Among them only cookie can be read/written both from frontend JS and backend.
JS Library
jQuery was created in 2006 by John Resig. It was designed to handle Browser Incompatibilities
and to simplify HTML DOM Manipulation, Event Handling, Animations, and Ajax.
For more than 10 years, jQuery has been the most popular JavaScript library in the world.
However, after JavaScript Version 5 (2009), most of the jQuery utilities can be solved with a few
lines of standard JavaScript.
Web API
When JavaScript runs in browser it can't do any OS operation except window.print() method
which open printer window of the OS.
All browsers have a set of built-in Web APIs to support complex operations, and to help
accessing data.
For example, the Geolocation API can return the coordinates of where the browser is located.
JS Class
ECMAScript 2015, also known as ES6, introduced JavaScript Classes.
JavaScript Classes are templates for JavaScript Objects.
If you want to give support for old browsers before 2015 then you have to write all of your
JavaScript code using version ES5.
NodeJs
Introduction
Node.js is an open-source server environment.
Node.js allows you to run JavaScript on the server.
Node.js uses asynchronous programming!
Node.js can generate dynamic page content.
Node.js can create, open, read, write, delete, and close files on the server.
Node.js can collect form data.
Node.js can add, delete, modify data in your database.
Node.js can be used as a Backend system with help of its HTTP package.
Unlike browser JavaScript when program in Node.js try using Latest LTS version of Node and
latest stable version of libraries and you can use latest JS version code without any doubt.
Getting Started
Create your app.js file and add following content.
Node Library
For Node.js npm and yarn are the two most popular package manager.
It creates a package.json in the project directory when install any library like below
npm install express
Node MVC framework
Express JS is a Fast, unopinionated, minimalist web framework for node.
npm install -g express-generator
Install package.json and Run Project
npm install
node app.js or npm start
Install a new plugin and save in package.json
npm install –save express-validator
Install a library globally and Restart project on change
npm install -g nodemon
nodemon
Template Language
https://pugjs.org/api/getting-started.html
https://expressjs.com/en/resources/template-engines.html
Routing
https://expressjs.com/en/guide/routing.html
Node Modules
Use the exports keyword to make properties and methods available outside the
module file.
mkdir simple-api
cd simple-api
npm init -y
app.listen(PORT, () => {
console.log(`Server is running on
http://localhost:${PORT}`);
});
1. Update package.json:
• Add a test script to package.json to run Jest.
"scripts": {
"start": "node index.js",
"test": "jest"
}
Explanation
1. Express API:
• app.get('/hello'): This route responds with "Hello, World!".
• app.get('/greet/:name'): This route responds with "Hello, <name>!" using
the name provided in the URL.
2. Unit Testing:
• supertest: Used to simulate HTTP requests and test responses.
• describe and it blocks: Jest functions to organize tests. Each it block
represents a single test.
• expect: Checks that the response matches our expectations, such as the
status code and message content.
TypeScript
Key Concepts in TypeScript for Beginners
1. Type Annotations
• TypeScript allows specifying types for variables, function parameters, and
return values, enabling type-checking during development.
• Example:
2. Interfaces
• Interfaces define the structure of an object, ensuring that objects meet
specific criteria.
• Example:
interface User {
name: string;
age: number;
isAdmin?: boolean; // optional property
}
class Animal {
name: string;
constructor(hello_name: string) {
this.name = hello_name;
}
makeSound(): void {
console.log("Sound...");
}
}
5. Enums
• Enums allow defining a set of named constants, making code more
readable.
• Example:
enum Direction {
Up,
Down,
Left,
Right
}
6. Generics
• Generics enable defining reusable components with variable types.
• Example:
function identity<T>(value: T): T {
return value;
}
mkdir hello-world-app
cd hello-world-app
npm init -y
2. Install dependencies
"scripts": {
"start": "node dist/index.js",
"build": "tsc",
"dev": "nodemon src/index.ts"
}
app.listen(PORT, () => {
console.log(`Server is running at
http://localhost:${PORT}`);
});
Hello, World!
Reactive framework
Core concept
Reactive frameworks, such as Next.js, enable developers to build web applications with virtual
DOM support, streamlining real-time data updates. They offer structured frameworks,
supported by extensive open-source communities.
Few Popular Frameworks
React
Vue.js
Angular
React is the most popular reactive framework due to its flexibility, speed, and vast ecosystem. It
leverages a virtual DOM for optimal performance and enables developers to build dynamic,
data-driven applications without manual DOM manipulation. With its strong open-source
community, React provides constant improvements and support.
Next.js is the best framework for using React to its fullest. It extends React’s capabilities by
adding features like server-side rendering (SSR), static site generation (SSG), and optimized
routing, making it ideal for production-grade applications.
Why React and Next.js Are the Best Combination
React: A powerful library for building responsive, interactive UIs with reusable components and
a vibrant ecosystem.
Next.js: Built on React, it takes the development experience further with support for SSR, API
routes, and automatic code splitting, making your application faster and more SEO-friendly.
Next.js Basics
function MyComponent() {
return (
<div>
</div>
);
o https://nextjs.org/learn
o Next.js with TypeScript Tutorial
o https://nextjs.org/docs/pages/api-reference/config/typescript
Components, Props, and State in Next.js
With Next.js, you leverage React components to build interactive UIs. Components can
be functional or class-based, accepting props for data passing.
function Counter() {
// Initialize a state variable 'count' with initial value
of 0
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
{/* Update state when the button is clicked */}
<button onClick={() => setCount(count +
1)}>Increment</button>
</div>
);
}
Example:
const element = <h1>Hello, {name}</h1>;
function HomePage() {
return <Image src="/path/to/image.jpg" alt="Description"
width={500} height={500} />;
}
Next.js Routing
In Next.js 13 and above, routing has been divided into two main concepts: App Router
and Pages Router. Here’s a breakdown:
• File-based Routing: Each folder in the app directory becomes a route, and
special files within those folders define components for that route.
• Routing Example:
• Features:
• Server Components: By default, components are rendered on the server,
improving SEO and performance.
• Layouts: You can define layout components (layout.js files) that are shared
across different routes.
• Colocation: You can keep styles, components, and assets within the route folder,
making the structure modular.
• API Routes: API routes are typically handled in a separate api folder within the
app directory.
Next.js enables API routes for building backend services within the same app, allowing
easy handling of server-side logic.
Details: https://nextjs.org/docs/pages/building-your-application/routing/api-routes
• File-based Routing: Each .js or .jsx file in the pages directory becomes a route.
• Routing Example:
• Features:
• Client-Side Routing: Ideal for Single Page Applications (SPAs) where client-side
interactivity is high.
Which to Use?
• App Router: For modular, server-rendered apps with layouts and better SEO.
• Pages Router: For simpler, client-rendered applications and legacy projects.
Details: https://nextjs.org/docs/pages/building-your-application/routing
Unit Test and Coverage
Here’s a TypeScript-based guide for setting up unit tests with coverage in a Next.js project using
Jest and React Testing Library.
1. Install Dependencies:
// jest.config.ts
import nextJest from 'next/jest';
const createJestConfig = nextJest({ dir: './' });
const customJestConfig = {
testEnvironment: 'jest-environment-jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/$1', // Alias support
},
transform: {
'^.+\\.tsx?$': 'ts-jest', // Use ts-jest for TypeScript files
},
collectCoverage: true,
collectCoverageFrom: ['components/**/*.tsx'],
coverageReporters: ['json', 'lcov', 'text', 'clover'],
};
// jest.setup.ts
import '@testing-library/jest-dom/extend-expect';
"scripts": {
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage"
}
1. Example Component:
Create a simple TypeScript component, Button.tsx:
// components/Button.tsx
import React from 'react';
interface ButtonProps {
onClick: () => void;
label: string;
}
// components/__tests__/Button.test.tsx
import { render, screen, fireEvent } from '@testing-library/react';
import Button from '../Button';
npm test
This will execute your tests, and you should see the results in the terminal.
Backends
OpenAPI (Swagger)
OpenAPI (Swagger) specification with explanations for a sample REST API:
openapi: 3.0.3
info:
title: Hotel Booking API
description: An API for managing hotel bookings, rooms, and
customers.
version: 1.0.0
servers:
- url: https://api.hotelbooking.com/v1
description: Production server
- url: https://sandbox.hotelbooking.com/v1
description: Sandbox server for testing
tags:
- name: Bookings
description: Operations related to hotel bookings
- name: Rooms
description: Operations related to rooms management
- name: Customers
description: Customer operations
paths:
/bookings:
get:
summary: Get all bookings
description: Returns a list of all bookings with details.
tags:
- Bookings
parameters:
- name: startDate
in: query
description: Filter bookings from this start date.
required: false
schema:
type: string
format: date
- name: endDate
in: query
description: Filter bookings up to this end date.
required: false
schema:
type: string
format: date
responses:
'200':
description: List of bookings retrieved successfully.
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Booking'
'400':
description: Invalid query parameters.
'500':
description: Server error.
post:
summary: Create a new booking
description: Adds a new booking for a customer.
tags:
- Bookings
requestBody:
description: Booking details to be created.
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/NewBooking'
responses:
'201':
description: Booking created successfully.
content:
application/json:
schema:
$ref: '#/components/schemas/Booking'
'400':
description: Invalid input data.
'500':
description: Server error.
components:
schemas:
Booking:
type: object
properties:
id:
type: string
format: uuid
description: Unique identifier for the booking.
customerId:
type: string
format: uuid
description: Customer ID associated with the booking.
roomId:
type: string
format: uuid
description: Room ID for the booking.
checkInDate:
type: string
format: date
description: Check-in date for the booking.
checkOutDate:
type: string
format: date
description: Check-out date for the booking.
NewBooking:
type: object
properties:
customerId:
type: string
format: uuid
description: Customer ID associated with the booking.
roomId:
type: string
format: uuid
description: Room ID to book.
checkInDate:
type: string
format: date
description: Check-in date.
checkOutDate:
type: string
format: date
description: Check-out date.
responses:
NotFound:
description: Resource not found.
content:
application/json:
schema:
type: object
properties:
message:
type: string
example: Resource not found.
Key Elements:
1. openapi: Specifies the OpenAPI version being used (3.0.3 in this case).
2. info: Metadata about the API, including title, description, and version.
3. servers: Lists the available servers where the API is hosted (production and
sandbox).
4. tags: Categories for grouping endpoints.
5. paths: Defines each endpoint (/bookings here), including:
• HTTP methods (get, post).
• summary and description: Brief and detailed explanations of the operation.
• parameters: Input parameters such as query, path, or headers.
• requestBody: Data sent to the API (for POST or PUT requests).
• responses: Defines possible responses with status codes.
6. components: Contains reusable schemas and response definitions:
• schemas: Define the structure of objects (e.g., Booking, NewBooking).
• responses: Common responses, e.g., “NotFound.”
Reference:
https://swagger.io/
Python Core
Basics
How to Install Python IDE
Step-1) To download and install Python, visit the official website of Python
https://www.python.org/downloads/ and choose your version
Step 2) Once the download is completed, run the .exe file to install Python. Now click on Install
Now.
What is a Variable in Python?
A Python variable is a reserved memory location to store values. In other words, a variable in a
python program gives data to the computer for processing
Python Variable Types
Every value in Python has a datatype. Different data types in Python are Numbers, List, Tuple,
Strings, Dictionary, etc. Variables in Python can be declared by any name or even alphabets like
a, aa, abc, etc.
How to Declare and use a Variable
a = 100
print(a)
Re-declare a Variable
f=0
print f
f = 'guru99'
print f
Python String Concatenation and Variable
a="Guru"
b = 99
print(a+str(b))
Python Variable Types: Local & Global
There are two types of variables in Python, Global variable and Local variable. When
you want to use the same variable for rest of your program or module you declare it
as a global variable, while if you want to use the variable in a specific function or
method, you use a local variable while Python variable declaration.
# Declare a variable and initialize it
f = 101
print f
# Global vs. local variables in functions
def someFunction():
# global f
f = 'I am learning Python'
print f
someFunction()
print f
Data Structure
Lists
Lists are very similar to arrays. They can contain any type of variable, and they can contain as
many variables as you wish. Example
mylist = []
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist[0]) # prints 1
print(mylist[1]) # prints 2
print(mylist[2]) # prints 3
Dictionary
A Dictionary in Python is the unordered and changeable collection of data values that
holds key-value pairs
Dict = {'Tim Cook': 18,'Charlie':12,'Tiffany':22,'Robert':25} print (Dict['Tiffany'])
Updating Dictionary
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Dict.update({"Sarah":9})
Delete Keys from the dictionary
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
del Dict ['Charlie']
Tuples
Tuples are used to store multiple items in a single variable.
A tuple is a collection which is ordered and unchangeable
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Conditional Loops
Conditions
Python uses boolean logic to evaluate conditions. The boolean values True and False are
returned when an expression is compared or evaluated. For example:
x=2
print(x == 2) # prints out True
print(x == 3) # prints out False
print(x < 3) # prints out True
The "and" and "or" boolean operators allow building complex boolean expressions, for
example:
name = "John"
age = 23
if name == "John" and age == 23:
print("Your name is John, and you are also 23 years old.")
The "in" operator could be used to check if a specified object exists within an iterable object
container, such as a list:
name = "John"
if name in ["John", "Rick"]:
print("Your name is either John or Rick.")
Loops
There are two types of loops in Python, for and while.
For loops iterate over a given sequence. Here is an example:
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
While loops repeat as long as a certain boolean condition is met. For example:
count = 0
while count < 5:
print(count)
count += 1
break is used to exit a for loop or a while loop, whereas continue is used to skip the current
block, and return to the "for" or "while" statement. A few examples:
for (i=0; i<10; i+=2)
for x in range(10, 2)
Functions
Functions are a convenient way to divide your code into useful blocks, allowing us to order our
code, make it more readable, reuse it and save some time. Also functions are a key way to
define interfaces so programmers can share their code.
Functions in python are defined using the block keyword "def", followed with the function's
name as the block's name. For example:
def my_function(name: string) -> tuple:
return "Hello From My Function!"+str(1)
Functions may also receive arguments (variables passed from the caller to the function). For
example:
def my_function_with_args(username, greeting):
print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))
Functions may return a value to the caller, using the keyword- 'return'. For example:
def sum_two_numbers(a, b=5):
return a + b
sum_two_numbers(1, 5)
How do you call functions in Python?
def my_function():
print("Hello From My Function!")
my_function()
def hello_world(a, *tuple, **dict):
hello_world(a=“name”, 1, 2, 4, name=”alex”, roll=19):
tuple=(1, 2, 4) dict={“name”: “alex”, “roll”=19}
File Handling
In Python, there is no need for importing external library to read and write files. Python
provides an inbuilt function for creating, writing, and reading files.
How to Create a Text File in Python
Step 1) Open the .txt file
f= open("guru99.txt","w+")
Step 2) Enter data into the file
for i in range(10):
f.write("This is line %d\r\n" % (i+1))
Step 3) Close the file instance
f.close()
You can read a file in Python by calling .txt file in a “read mode”(r).
Step 1) Open the file in Read mode
f=open("guru99.txt", "r")
Step 2) We use the mode function in the code to check that the file is in open mode. If yes, we
proceed ahead
if f.mode == 'r':
Step 3) Use f.read to read file data and store it in variable content for reading files in Python
contents =f.read()
with open(“file.txt”, “r”) as f:
f.readlines()
here..
Classes and Objects
Objects are an encapsulation of variables and functions into a single entity. Objects get their
variables and functions from classes. Classes are essentially a template to create your objects.
A very basic class would look something like this:
class MyClass:
“””
variable = "blah"
def function(self):
print("This is a message inside the class.")
“””
To access the variable inside of the newly created object "myobjectx" you would do the
following:
class MyClass:
variable = "blah"
def function(self):
print("This is a message inside the class.")
myobjectx = MyClass(“hello”)
myobjectx.variable
To access a function inside of an object you use notation similar to accessing a variable:
myobjectx.function()
Modules
Modules in Python are simply Python files with a .py extension. The name of the module will be
the name of the file. A Python module can have a set of functions, classes or variables defined
and implemented. In the example above, we will have two files, we will have:
draw/
draw /game.py
draw /draw_a_game.py
draw /__init__.py
Modules are imported from other modules using the import command. In this example, the
game.py script may look something like this:
We may also use the import * command to import all objects from a specific module, like this:
from draw import *
def main():
result = play_game()
draw_game(result)
References
https://www.learnpython.org/
https://www.guru99.com/python-tutorials.html
https://docs.python.org/3.9/tutorial/index.html
Web Frameworks
Django
Why Django? Key Advantage of Django
Here are the main advantages of Django:
Django is easy to set up and run. It offers a variety of options to get started
It provides a ready-to-use user interface for administrative activities
It enables multilingual websites by using its built-in internationalization system
Django helps you to provide end-to-end application testing
Helps you to document your API with an HTML output
REST Framework has rich support for several authentication protocols
Features of Django
Below are the features of Django: 10 Behavioral Interview Questions and Answers
Components of Django Commented [S1]: Make Calibri, and 12 as font size, check
DB Section @Arif
Form:
Django has a powerful form library which handles rendering forms as HTML. The library
helps in validating submitted data and converting it to Python types.
Authentication:
It handles user accounts, groups, cookie-based user sessions, etc.
Admin:
It reads metadata in your models to provide a robust interface which can be used to
manage content on your site.
Internationalization:
Django provides support for translating text into various languages, locale-specific
formatting of dates, times, numbers, and timezones.
Security:
Django provides safeguard against the following attacks:
Cross-Site Request Forgery (CSRF)
Cross-site scripting
SQL injection
Clickjacking
Remote code execution
Django Basics
Install Django by giving following command-pip install django
Creating a Project
To initiate a project of Django on Your PC, open Terminal and Enter the following command
django-admin startproject projectName
A New Folder with name projectName will be created. To enter in the project using terminal
enter command cd projectName
Now run, python manage.py runserver
To create a basic app in your Django project you need to go to directory containing manage.py
and from there enter the command: python manage.py startapp projectApp
To consider the app in your project you need to specify your project name in INSTALLED_APPS
list as follows in settings.py:
INSTALLED_APPS = [
'projectApp'
]
Now in the list of URL patterns, you need to
specify app name for including your app urls.
Here is the code for it –
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
# Enter the app name in following syntax for
this to work
path('', include("projectApp.urls")),
]
Django Views
Django views are divided into two major categories: -
Function-Based Views
Class-Based Views
Function based view Example –
Let’s Create a function-based view list view to display instances of a model. Let’s create a view
and template for the same. In geeks/views.py,
Class-based views are simpler and efficient to manage than function-based views. A function-
based view with tons of lines of code can be converted into class-based views with few lines
only. This is where Object-Oriented Programming comes into impact.
Django Models
A Django model is the built-in feature that Django uses to create tables, their fields, and various
constraints. In short, Django Models is the SQL of Database one uses with Django
Basics of a model include –
Whenever we create a Model, Delete a Model, or update anything in any of models.py of our
project. We need to run two commands makemigrations and migrate
So when we run, Python manage.py makemigrations
SQL Query to create above Model as a Table is created and Python manage.py migrate
creates the table in the database.
Django Forms
When one creates a Form class, the most important part is defining the fields of the form. Each
field has custom validation logic, along with a few other hooks.
Django handles three distinct parts of the work involved in forms:
Django CLI
Django provides a mechanism to create custom management commands that can be executed
via the manage.py script. These commands can be used for tasks like data processing,
maintenance scripts, or any application-specific logic.
Custom Management Commands
1. Set Up the Directory Structure
Custom commands are stored in the management/commands directory inside an app.
arg_value = options['arg_name']
YourModel.objects.create(name="Dummy Data")
def validate():
return redirect(url_for("success"))
return redirect(url_for("login"))
The abort() function is used to handle the cases where the errors are involved in the requests
from the client side, such as bad requests, unauthorized access and many more. Example:
def validate():
return redirect(url_for("success"))
else:
abort(401)
Flask WTF
WTF stands for WT Forms which is intended to provide the interactive user interface for the
user. The WTF is a built-in module of the flask which provides an alternative way of designing
forms in the flask web applications.
Install flask WTF pip install flask-wtf
Example:
Unit testing is a method of testing individual units of code (functions, methods, or classes) in
isolation. Python provides the built-in unittest module for this purpose, but frameworks like
pytest are also popular.
File: app.py
app = Flask(__name__)
@app.route('/')
def home():
return jsonify({'message': 'Welcome to Flask!'})
@app.route('/add', methods=['POST'])
def add():
data = request.get_json()
result = data['a'] + data['b']
return jsonify({'result': result})
if __name__ == '__main__':
app.run(debug=True)
Step 2: Write Unit Tests for the Flask Application
Create a test file where you’ll write test cases for your Flask app.
File: test_app.py
import unittest
from app import app
class FlaskAppTests(unittest.TestCase):
def setUp(self):
# Set up a test client
self.app = app.test_client()
self.app.testing = True
def test_home(self):
response = self.app.get('/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json, {'message': 'Welcome to
Flask!'})
def test_add(self):
response = self.app.post('/add', json={'a': 2, 'b': 3})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json['result'], 5)
def test_add_invalid_data(self):
response = self.app.post('/add', json={'a': 'two', 'b': 3})
self.assertNotEqual(response.status_code, 200) # Should
handle invalid input gracefully
if __name__ == '__main__':
unittest.main()
coverage report
4. To create an HTML report for better visualization:
coverage html
Identify untested parts of your application and write additional tests to cover them.
2. Rename test_app.py to follow pytest conventions (e.g., keep the file name as
test_*.py).
3. Run tests:
Golang
Course Brief Time: 8 hours
Setup Environment
Installation: https://golang.org/doc/install
IDE:
o Goland (Activator)
o VSCode with Go Extension
Prepare Workspace
o Create go workspace directory inside your home directory
Windows: C:/Users/name/go/src
Mac/Ubuntu: $HOME/go/src
o Few important commands
Set GOPATH:
Windows: SET GOPATH=C:/Users/<name>/go/bin
Mac/Ubuntu: export GOPATH=$HOME/go/bin
Get Go Path: go env GOPATH
Set GOBIN:
Windows: SET GOBIN=C:/Users/<name>/go/bin
Mac/Ubuntu: export GOBIN=$HOME/go/bin
Check Go environment variables: go env
Run go program: go run main.go
Build go program: go build main.go
Data types: In the Go programming language, data types refer to an extensive system
used for declaring variables or functions of different types. The type of a variable
determines how much space it occupies in storage and how the bit pattern stored is
interpreted.
o Boolean types: They are boolean types and consists of the two predefined
constants: (a) true (b) false
o Numeric types: They are again arithmetic types and they represents a) integer
types or b) floating point values throughout the program.
o String types: A string type represents the set of string values. Its value is a
sequence of bytes. Strings are immutable types that is once created, it is not
possible to change the contents of a string. The predeclared string type is string.
o Derived types: They include (a) Pointer types, (b) Array types, (c) Structure types,
(d) Union types and (e) Function types f) Slice types g) Interface types h) Map
types i) Channel Types
More details: https://www.tutorialspoint.com/go/go_data_types.htm
Variables: A variable is nothing but a name given to a storage area that the programs
can manipulate. Each variable in Go has a specific type, which determines the size and
layout of the variable's memory, the range of values that can be stored within that
memory, and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character.
It must begin with either a letter or an underscore. Upper and lowercase letters are
distinct because Go is case-sensitive.
o Static Type Declaration: var x float64
o Dynamic Type Declaration / Type Inference: y := 42
o Mixed Variable Declaration: var a, b, c = 3, 4, "foo"
Constants: Constants are treated just like regular variables except that their values
cannot be modified after their definition. Example: const LENGTH int = 10
Operators: An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. Go language is rich in built-in operators
and provides the following types of operators:
o Arithmetic Operators: +, -, *, /, %, ++, --
o Relational Operators: ==, !=, >, <, >=, <=,
o Logical Operators: &&, ||, !
o Bitwise Operators: &, |, ^, <<, >>
o Assignment Operators: =, +=, -=, *=, /=, %=, <<=, >>=, &=, |=, ^=1
o Miscellaneous Operators:
&: return address
*: return pointer
Array:
package main
import "fmt"
func main() {
var theArray [3]string
theArray[0] = "India"
theArray[1] = "Canada"
theArray[2] = "Japan"
fmt.Println(theArray)
Slice: Slices looks like array in golang but it is a bit flexible and powerful than array.
Array is fixed but slice is variable. Slices can be resized using the built-in append
function.
var theArray [3]string // Array
var theArray []string // Slice
var intSlice = make([]int, 10) // Slice
Slice example:
package main
import (
"fmt"
"reflect"
)
func main() {
var intSlice = make([]int, 10) // when length and
capacity is same
var strSlice = make([]string, 10, 20) // when length and
capacity is different
fmt.Printf("intSlice \tLen: %v \tCap: %v\n", len(intSlice),
cap(intSlice))
fmt.Println(reflect.ValueOf(intSlice).Kind())
fmt.Printf("strSlice \tLen: %v \tCap: %v\n", len(strSlice),
cap(strSlice))
fmt.Println(reflect.ValueOf(strSlice).Kind())
}
Length is the current number of element and capacity is the number of elements a slice
can store.
More details: https://www.golangprograms.com/go-language/slices-in-golang-
programming.html
Map: A map is a data structure that provides you with an unordered collection of
key/value pairs (maps are also sometimes called associative arrays in Php, hash tables in
Java, or dictionaries in Python). Maps are used to look up a value by its associated key.
You store values into the map based on a key.
package main
import "fmt"
func main() {
var employee = make(map[string]int)
employee["Mark"] = 10
employee["Sandy"] = 20
fmt.Println(employee)
employeeList := make(map[string]int)
employeeList["Mark"] = 10
employeeList["Sandy"] = 20
fmt.Println(employeeList)
}
Structs: Structs are the only way to create concrete user-defined types in Golang. Struct
types are declared by composing a fixed set of unique fields. Structs can improve
modularity and allow to create and pass complex data structures around the system.
You can also consider Structs as a template for creating a data record, like an employee
record or an e-commerce product.
Struct with primitive data type:
package main
import "fmt"
type rectangle struct {
length float64
breadth float64
color string
}
func main() {
fmt.Println(rectangle{10.5, 25.10, "red"})
}
JSON struct, marshal and unmarshal: We can create a struct for JSON data. The JSON
data can be encoded and decoded with a defined struct in the following way.
package main
import (
"fmt"
"encoding/json"
)
type Employee struct {
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
City string `json:"city"`
}
func main() {
json_string := ` {
"firstname": "Rocky", "lastname":
"Sting", "city": "London" }`
emp1 := new(Employee)
json.Unmarshal([]byte(json_string), emp1)
fmt.Println(emp1.FirstName, emp1.LastName, emp1.City)
emp2 := new(Employee)
emp2.FirstName = "Ramesh"
emp2.LastName = "Soni"
emp2.City = "Mumbai"
jsonStr, _ := json.Marshal(emp2)
fmt.Printf("%s\n", jsonStr)
}
Decision making:
Decision making with if, else and else if:
package main
import ("fmt")
func main() {
x := 100
if x == 50 {
fmt.Println("Germany")
} else if x == 100 {
fmt.Println("Japan")
} else {
fmt.Println("Canada")
}
}
Loop:
package main
import "fmt"
func main() {
for k := 1; k <= 10; k++ {
fmt.Println(k)
}
k = 1
for k <= 10 {
fmt.Println(k)
k++
}
for k := 1; ; k++ {
fmt.Println(k)
if k == 10 {
break
}
}
}
Range:
package main
import "fmt"
func main() {
// Example 1
strDict := map[string]string{"Japan": "Tokyo", "China":
"Beijing", "Canada": "Ottawa"}
for index, element := range strDict {
fmt.Println("Index :", index, " Element :", element)
}
// Example 2
for key := range strDict {
fmt.Println(key)
}
// Example 3
for _, value := range strDict {
fmt.Println(value)
}
}
Function: func keyword has been used to declare a function in golang. We can return
multiple variable from a function in golang.
package main
import "fmt"
// SimpleFunction prints a message
func SimpleFunction() {
fmt.Println("Hello World")
}
func main() {
SimpleFunction()
}
Scope: In golang a variable declared inside main function is a local variable, outside of
main is a global variable and a variable/function outside of main with capital character
can be accessed from any other package.
package main
import "fmt"
package main
import (
"fmt"
"time"
)
func main() {
go concurrentFunc("First process")
go concurrentFunc("Second process")
go concurrentFunc("Third process")
time.Sleep(1 * time.Second) // to wait
main function
}
Channel: Go provides a mechanism called a channel that is used to share data between
goroutines. When you execute a concurrent activity as a goroutine a resource or data
needs to be shared between goroutines, channels act as a conduit(pipe) between the
goroutines and provide a mechanism that guarantees a synchronous exchange.
A channel is created by the make function, which specifies the chan keyword and a
channel's element type.
Unbuffered := make(chan int) // Unbuffered channel
buffered := make(chan int, 10)// Buffered channel
Example:
package main
import (
"fmt"
)
func main() {
data := make(chan string)
go concurrentFunc("First process", data)
message := <-data
fmt.Println(message)
}
Type casting:
Structure (convert string to int): intVar, err := strconv.Atoi(strVar)
More details: https://www.golangprograms.com/go-language/integer-float-string-
boolean.html
if err != nil {
fmt.Println(err)
}
HTTP request:
Get request:
package main
import (
"io/ioutil"
"log"
"net/http"
)
func main() {
resp, err :=
http.Get("https://jsonplaceholder.typicode.com/posts")
if err != nil {
log.Fatalln(err)
}
//We Read the response body on the line below.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
//Convert the body to type string
sb := string(body)
log.Printf(sb)
}
POST Request:
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"net/http"
)
func main() {
//Encode the data
postBody, _ := json.Marshal(map[string]string{
"name": "Toby",
"email": "[email protected]",
})
responseBody := bytes.NewBuffer(postBody)
//Leverage Go's HTTP Post function to make request
resp, err := http.Post("https://postman-echo.com/post",
"application/json", responseBody)
//Handle Error
if err != nil {
log.Fatalf("An Error Occured %v", err)
}
defer resp.Body.Close()
//Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
sb := string(body)
log.Printf(sb)
}
Golang Assignment
Develop a REST API with POST request for user registration with following fields: First
Name, Last Name, Email, Phone, Password, Date of birth
o Use PostgreSQL to store those data
o Use appropriate data type
o Store password hash instead of direct string
o Implement appropriate form validation
o API should return JSON including success with user id or error with message
Develop a REST API with POST request to upload user image with following fields: image
and user id
Implement a login API with Email and Password with GET request.
All the API should work under separate goroutine
Web Frameworks
Beego is a RESTful HTTP framework for the rapid development of Go applications including
APIs, web apps and backend services with integrated Go specific features such as interfaces and
struct embedding.
Beego architecture:
File structure:
Setup environment: https://www.golangprograms.com/golang/beego-setup-installation/
GET and POST request: https://www.golangprograms.com/golang/beego-get-post-routing/
Routing: https://www.golangprograms.com/golang/beego-route-contoller-get-method/
Template parsing: https://beego.me/docs/mvc/view/view.md
Develop a homepage with a banner and three horizontal sections: Popular, Trending
and TV series. Each item should show horizontal list of movie images and title receives
from API.
Implement movie details page with movie image, title, star rating, details and play
trailer feature
Develop a REST API in Golang to store favorite movies in DB
Implement API to add movies into favorite list
Show list of favorite movies in a new page
Cloud Infrastructure
Deployment tools and techniques
Cloud Infrastructure
The collection of hardware and software elements needed to enable cloud computing. It includes
computing power, networking, and storage, as well as an interface for users to access their Commented [S2]: Make Calibri, and 12 as font size, check
virtualized resources, without direct active management by the user. DB Section @Rajib Biswas
Cloud computing has created the opportunity for organizations to access the data storage and
computing capabilities that they require, on an as-needed basis and with a significantly reduced
up-front cost, instead of establishing their own on-premise IT infrastructure. Some of the top
cloud service providers
VPC
A virtual private cloud (VPC) is a virtual network dedicated to one AWS account. It’s logically
isolated from other virtual networks in AWS. One can lunch AWS resources under the VPC he
has. Under VPC you will get other related service like Subnet, Route Tables, Internet Gateways,
Elastic IPs, Network ACLs, Security Groups etc.
S3
Simple Storage Service - This is an object Storage Service, provides data availability, stability,
security and performance. Durability 99.999999999 % (11 9’s) and grows automatically with
your needs, pay as you use policy. Keeps copy of data on multiple devices on multiple zones.
The total volume of data and number of objects you can store are unlimited. Individual Amazon
S3 objects can range 0 bytes to 5TB.
Types: (Provides configurable life cycle policy)
S3 Standard
S3 Intelligent-Tiering
S3 IA (Infrequent Access)
S3 One Zone-IA
Amazon Glacier
S3 Glacier Deep Archive
CloudFront
CDN service that securely delivers data, videos, application, and APIs to customers globally with
low latency, high transfer speeds. CloudFront is directly connected with all AWS services /
Global infrastructure. Works as a caching server near you.
Currently AWS has a Global network of 230+ Points of Presence – 218 Edge Location & 12
Regional Edge Caches.
Some benefit:
ô Makes content delivery faster for static web content.
ô Provides encrypted communication.
ô DDoS protection with layer 3 & 4.
ô Application layer protection.
Indirect:
RDS
Amazon Relational Database Service (Amazon RDS), a managed service which makes it easy to
set up, operate, and scale a relational database in the cloud. It reduces administration tasks
such as hardware provisioning, database setup, patching and backups. It frees you to focus on
your applications so you can give them the fast performance, high availability, security and
compatibility they need. Aws RDS provides you with six familiar database engines to choose
from.
o Amazon Aurora
o PostgreSQL
o MySQL,
o MariaDB
o Oracle Database
o SQL Server
NoSQL
NoSQL databases (aka "not only SQL") are non-tabular, and store data differently than
relational tables.
NoSQL database have the following facilities:
Flexibility: NoSQL databases generally provide flexible schemas that enable faster and
more iterative development. The flexible data model makes NoSQL databases ideal for
semi-structured and unstructured data.
Scalability: NoSQL databases are generally designed to scale out by using distributed
clusters of hardware instead of scaling up by adding expensive and robust servers. Some
cloud providers handle these operations behind-the-scenes as a fully managed service.
High-performance: NoSQL database are optimized for specific data models and access
patterns that enable higher performance than trying to accomplish similar functionality
with relational databases.
Highly functional: NoSQL databases provide highly functional APIs and data types that
are purpose built for each of their respective data models.
AWS provides different types of NoSQL database.
Route53
AWS Route 53: is a scalable & highly available Domain Name System (DNS) web service. Its
easily routes traffic to all its pointed services as well as route users to infrastructure outside of
AWS.
Key Features:
• Domain Registration
• Resolver
• Traffic flow
• Latency based routing
• DNS Failover
• Health checks and monitoring
• ELB, S3 integration
SQS
Simple Queue Service
A fully managed message queuing service that enables you to decouple and scale microservices,
distributed systems, and serverless applications.
With SQS one can send, store, and receive messages between software components at any
volume, without losing messages or requiring other services to be available.
Queue Types:
Standard queue.
FIFO
Elastic Beanstalk
Elastic Beanstalk, one can quickly deploy and manage applications in the AWS Cloud without
having to learn about the infrastructure that runs those applications. Elastic Beanstalk reduces
management complexity without restricting choice or control. You simply upload your
application, and Elastic Beanstalk automatically handles the details of capacity provisioning, load
balancing, scaling, and application health monitoring. Elastic Beanstalk supports applications
developed in Go, Docker, Java, .NET, Node.js, PHP, Python, and Ruby.
Elasticsearch
Elasticsearch is an open-source, RESTful, distributed search and analytic engine built on Apache
Lucene.
Elasticsearch usages a data structure called an inverted index, which is allows to allow very fast
full-text search. An inverted index lists every unique world that appears in any documents all of
the documents each word occurs in.
Known as ELK (Elasticsearch, Logstash, Kibana).
Why use Elasticsearch?
Elasticsearch is free
Elasticsearch is fast
Elasticsearch is distributed by nature
o Elasticsearch comes with a wide set of features
The Elastic Stack simplifies data ingest, visualization, and reporting.
Elasticsearch used for.
Application search
Website search
Logging and log analytics
Geospatial data analysis and visualization
Security analytics
Business analytics
Lambda
AWS Lambda is a serverless computing service provided by Amazon Web Services (AWS).
Lambda lets you run code without provisioning or managing servers. Lambda runs your code on
a high-availability compute infrastructure and performs all of the administration of the
compute resources, including server and operating system maintenance, capacity provisioning
and automatic scaling, code monitoring and logging.
AWS Lambda natively supports Java, Go, PowerShell, Node.js, C#, Python, and Ruby code, and
provides a Runtime API which allows you to use any additional programming languages to
author your functions.
CloudFormation
CloudFormation - Infrastructure as Code, is a service that gives an easy way to create a
collection of related AWS and third-party resources, and provision and manage them in an
orderly and predictable fashion. You can create templates using YAML or JSON for the service
or application architectures you want and have, AWS CloudFormation use those templates for
quick and reliable provisioning of the services or applications (called “stacks”). You can also
easily update or replicate the stacks as needed.
Linux (OS)
Linux is a Unix-like, open source and community-developed operating system. An operating
system is the software that directly manages a system’s hardware and resources, like CPU,
memory, and storage. Some popular Linux distribution
Ubuntu
Fedora
CentOS
Linux Mint Cinnamon
Debian GNU/Linux
Linux terminal is the place where one will run commands. Some basic commands to learn:
Docker
Docker is a software platform that allows you to build, test, and deploy applications quickly, it’s
use OS-level virtualization to deliver software in packages called containers & they are isolated
from one another and bundle their own software, libraries and configuration files; they can
communicate with each other through well-defined channels. The software that hosts the
containers is called Docker Engine.
Some basic docker command:
# Pull an image from a registry
docker pull myimage:1.0
# Re-tag a local image with a new image name and tag
docker tag myimage:1.0 myrepo/myimage:2.0
# Push an image to a registry
docker push myrepo/myimage:2.0
# Build an image from the Dockerfile in the current directory and tag the image
docker build -t myimage:version .
# List all images that are locally stored with the Docker Engine
docker image ls
# Delete an image from the local image store
docker image rm alpine:3.4
# Run a container from the Alpine version 3.9 image, name the running container “web” and
expose port #5000 externally, mapped to port 80 inside the container.
docker container run --name web -p 5000:80 alpine:3.9
# Stop a running container
docker container stop web
# List only active containers
docker ps
# List all containers
docker ps -a
# Stop a container
docker stop [container-name|container-id]
# List the networks
docker network ls
# List the running containers (add --all to include stopped containers)
docker containerName/ID ls
# Delete all running and stopped containers
docker container rm -f $(docker ps -aq)
# Print the last 100 lines of a container’s logs
docker container logs --tail 100 containerName/ID
# Print the container’s logs (use -f to follow)
docker container logs containerName/ID
Docker Compose
Docker Compose is a tool for running multi-container applications on Docker defined using the
Compose file format. A Compose file is written using YAML, which used to define how the one or
more containers that make up your application are configured. Once you have a Compose file,
you can create and start your application with a single command: docker-compose up.
Compose is basically a three-step process:
Define your app’s environment with a Dockerfile so it can be reproduced anywhere.
Define the services that make up your app in docker-compose.yml so they can be run
together in an isolated environment.
Run docker-compose up, which bring your app to live.
Below is an example of docker-compose file.
version: '3'
services:
web:
image: nginx
db:
image: mysql
ports:
- "3306:3306"
environment:
- MYSQL_ROOT_PASSWORD=password
- MYSQL_USER=user
- MYSQL_PASSWORD=password
- MYSQL_DATABASE=demodb
GIT
Open-Source Distributed Version Control System, is a tool used for source code management,
able to tracking changes in any set of files, used for coordinating work among programmers for
collaboratively developing source code during software development.
Some git command that we use very frequently:
## Clone a project
git clone [URL]
## Pull a branch
git pull
## downloads commit, files, and refs from a remote repository into your local repo.
git fetch
## lists all the files that have to be committed
git status
## list the version history for the current branch
git log
## list branch
git branch
## check all remote branch
git branch -a
## to create a new branch
git branch branchName
## to delete a branch
git branch -d branchName
## switch from one branch to another.
git checkout branchName
## Create a new branch and switch to it.
git checkout -b branchName
## push your update to remote
git add .
git commit -m "messages"
git push
## push a new local branch to remote
git push -u origin branchName
## merge a branch
git merge branchName
## diff of what is changed but not staged
git diff
## diff of what is staged but not yet committed
git diff --staged
IDE
An integrated Development environment (IDE) is software for building applications that
combines common developer tools into a single graphical user interface (GUI). Typically
consists of:
Automation Tools
Automation Software is an application that has functionalities to develop, manage, and monitor
automated processes for IT enterprise. IT processes are scattered across multiple environments,
tools, and technologies, this is a difficult task to manage. Automation software is used for
automating repetitive tasks and manual processes so that there will be cost savings and reduced
human errors. These tools have features to monitor and manage distributed IT environments.
Top automation software
1. Ansible
2. Terraform
3. Jenkins
4. Chef
5. Puppet
Let’s see the key difference between Ansible vs Terraform
Ansible Terraform
Can deploy apps on the top of infrastructure. Can deploy Load balancers, VPCs, etc.
With Ansible, you need to dictate each step Terraform can carry out all steps to present
to achieve the end result. the final output, once given the end
instruction.