0% found this document useful (0 votes)
22 views

Coding4women Mainfile

The document provides an introduction to a coding course for women that teaches the Go programming language. The 8-week course will cover basic Go organization, data types, and creating a website backend. Students will learn functions, variables, control flow, and complete a final project. The document encourages participation, asks students to set up tools like Go and GitHub, and introduces key Go concepts like packages, importing, and data types.

Uploaded by

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

Coding4women Mainfile

The document provides an introduction to a coding course for women that teaches the Go programming language. The 8-week course will cover basic Go organization, data types, and creating a website backend. Students will learn functions, variables, control flow, and complete a final project. The document encourages participation, asks students to set up tools like Go and GitHub, and introduces key Go concepts like packages, importing, and data types.

Uploaded by

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

CODING FOR

WOMEN
Diana Adamczyk, Daisy Murray
WHAT YOU WILL ACHIEVE BY
COMPLETING THIS COURSE

AN INTRODUCTION TO YOU WILL CREATE YOUR YOU WILL BE CONFIDENT


CODING WITH GO. OWN WEBSITE. TO CONTINUE LEARNING TO
CODE
JOIN OUR DISCORD SERVER &
WHATSAPP GROUP

Scan to join Discord


www. discord.com
HOW THIS COURSE WORKS
AND EXPECTATION
• 8️⃣ weeks
• Please attend in person if you can, you will learn more
• We will set homework every week ✅
• The more you put in, the more you will get out
• Trust the process, this is a new skill, it takes take for knowledge to stick! 🧠
• Please ask for help when you need it. We love it when you ask questions 💖
WHAT WILL WE LEARN
We will learn basic organisation of Go, data types and will create the backend of your own
website.
Week 1 : introductions, set up,what is go, create your first function
Week 2: data types in variables, control flow
Week 3: Advanced functions, composite data types
Week 4: Progress check in
Week 5: Start project
Week 6: Project
Week 7:Project
Week 8: Finish Project
WHAT IS GO?
A free, open-source programming language created at Google by Robert Griesemer, Ken
Thompson and Rob Pike.

First release was 2011.

The goals of the Go project were to eliminate the slowness and clumsiness of software
development at Google, and thereby to make the process more productive and scalable.
The aims of Go are to be expressive, fast, efficient, reliable and simple to write.
•Simple Syntax
•Compiled Language
•Statically typed
•Concurrency
•Dependency management

•Go is used for server-side (backend) programming, web development, game


development, cloud-based programming, and even Data Science. It is also popular
for making command-line tools.
•Today, many tech giants use Go like Google, Netflix, Twitch, Ethereum, Dropbox,
Kubernetes, Docker, Heroku, and lots more.
https://uk.indeed.com/
q-golang-developer-jobs.html?vj
k
JOB PROSPECTS? =58345cabd84f0d76
LET’S GET YOU SET UP!
If you have your laptop, download Go
Also download VS code
Create an account on GitHub to upload and save your work!
LET’S MEET
EACH OTHER
PLEASE FILL OUT THE
GOOGLE FORM
https://forms.gle/U8ssQZyA1s1PHyCB8

- please log onto your Discord Account, you will find this link
- we will share resources here
WEEK 1
•Introductions
•Write your first functions!
•Installing Go and VS code
•Questions?

02/28/2024
PASTE THE FOLLOWING INTO
YOUR FILE
Add picture house and door

Declares the package the code belongs to

Make the fmt (format) package available


for use

Declare the main function

<package>.<function>( X x your logic x X)


WE’VE ENCOUNTERED 3
KEYWORDS SO FAR
(THERE ARE 25 KEY WORDS)
package : All code in Go is organised into packages. Each package corresponds to a
single idea.

import : we can import premade packages, to call a collect of functions we want to


use.
 The math package provides functions like sqrt (square root), Sin, Cos, Tan
 The fmt package provides functions to format text Println(), Printf(), append()

func : declares a function


 Its followed by () {XXX code inside}
FUNC : DECLARES A
FUNCTION

The body of each function is enclosed in curly brackets. This is how Go knows
where each function begins and ends
func main () is special….

When you run a program written in Go, execution begins at the main function in the
main package. Without main the Go complier will report an error, because it doesn’t
know where the program should start.
COMMENTS – TO MAKE YOUR
CODE MORE READABLE
//this is how you add a comment
/* you can block out several lines of
cooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooode like this */
WHY DIDN’T
THIS RUN?
Opening curly brackets need to be on same line
as the func declaration
WHY DIDN’T THIS
RUN?
No package was declared, every file needs to be within a package.
WHERE
DOES A GO
PROGRAM
START?
A program starts at the main function
in the main package
LET’S CREATE OUR FIRST
PROGRAM IN GO!
1. create a file called “ isAlpha.go”

inside, create a function “PrintAlphabet” that prints the Latin alphabet in lowercase
on a single line.
A line is a sequence of characters preceding the end of line character ('\n').
To run your code type go run <name of program>

The ‘go run’ command executes the program. Your can type in the file name
‘main.go’ or ‘.’ which means the current directory file I am in.

! Don’t forget the file extension !n ’<filename>.go’ when calling files


EXERCISE 2
Write a file called “PrintDigits.go”

inside, write a function “PrintDigits” that prints the decimal digits in ascending order
(from 0 to 9) on a single line.
A line is a sequence of characters preceding the end of line character ('\n').
EXERCISE 3
Write a file called “reverseAlphabet.go”

Inside, write a function “ReverseAlphabet” that prints the Latin alphabet in


lowercase on a single line.
A line is a sequence of characters preceding the end of line character ('\n').

02/28/2024
NOW UPLOAD YOUR WORK!
git add .

git commit –m “write a message on what you’re uploading”

git push

02/28/2024
IMPORTANT COMMANDS
FROM THE TERMINAL
Use these commands to navigate from the terminal:

cd -> Allows you to change directory


 cd ../ -> go back one file level
 cd <filename> / you can write the path to your file

ls -> list the contents of the current directory


mkdir -> create a new directory / several directories
touch -> create an empty file (s)
echo -> prints a string of text, or value of a variable to the terminal

see more commands at https://ss64.com/bash/


02/28/2024
WEEK 2 Coding for Women

02/28/2024
WEEK 2
By the end of this lesson
-create more functions
- learn about variables and data types
- perform operations
WHAT WE DID LAST WEEK
- set up
-made our first function
ANY
QUESTION
S?
VARIABLES
A variable is a name that represents data stored in the computer’s memory.
All variables when declared, whether explicitly or implicitly must have a type.

Basic data types:

• Numbers think of a variable as a


container that holds a value
• Strings
like a box that holds an
• Booleans object.
DIFFERENT WAYS OF
DECLARING A VARIABLE
Declared using the var key word
Explicit declaration

:= symbol for short


way of declaring

Implicit declaration When declaring a variable


without specifying a type
the variable’s type is inferred by the
value on the right hand side.
Data Type Description Example

string A string of characters var message = “Hi there”

Int A whole number var cars = 12

bool A true or false value var isEmpty = false

rune a single character, a Unicode point var r rune = ' 你 '


byte a single character, from ASCII table var b byte = 'A'
When you manipulate a string in a Go program, you are effectively operating on the
sequence of runes that make up the string.

A rune represents a Unicode code point, which is an integer value that corresponds
to a particular character or symbol.

Runes allow for the representation of characters and symbols from many different
writing systems and languages.
Variables that are not set to a value, are given their zero value

0 for numeric. Types


False for Boolean type
“” (empty string) for strings

“string sentence”
WHEN NAMING A VARIABLE
Rule Example
CANNOT be a key word break, continue, func , main
CANNOT contain arithmetic operators a+b%c
CANNOT contain punctuation/special characters &%$*£,!
CANNOT contain spaces (only underscores) my_msg
MUST start with a letter msg
CAN contain numbers elsewhere msg1
CAN contain mixed case camelCase
QUIZ ON VARIABLES
Q1. How do you (explicitly) declare a variable? What is the key word?

1. var
2. var <nameVariable> type
3. variable name string
Can you list some basic types for variables?

1. Bool
2. String
3. int
4. rune
5. byte
Q3. Which of these variables is correctly initialized?

1. variable a = “Daisy”
2. var b string = “Daisy”
3. var c string = Daisy
FUNCTIONS
A block of code that performs a specific task
or returns a value.

Functions in Go are defined using the func keyword,


followed by the name of the function, a list of parameters (if any), and the
return type (if any)
Functions in Go can be called from other parts of your program, passing in
arguments and receiving the return values.

Here's an example of calling the add function we defined earlier:

This code calls the add function with the arguments 2 and 3, and assigns the result (5) to the variable sum.
Go functions accept 0 or more parameters (inputs)

So far we have just been printing values directly onto the terminal and then the computer
forgets them!

However, if you want to keep the values to use, add a ‘ return ‘ keyword to the function.
You state what type of variable(s) you are returning. It has to be the last line of your
function.

You can invoke a function by calling it (i.e. writing it’s name) and you can pass arguments
inside the brackets
Things to keep in mind!

 when variables are declared, they either explicitly or implicitly are assigned a type even
before your program runs.

 Go requires that every variable you declare gets used somewhere in your program

 You can assign new values to existing variables, but they need to be values of the same
type.

 A variable declared within a function only exists that function


ARITHMETIC OPERATORS
COMPARISON OPERATORS

02/28/2024
LOGICAL OPERATORS

02/28/2024
EXERCISE
Create a function called IsEven

When you input a number to the function, it will print to the terminal “Even” if the
number is even, “Odd” if the number is odd.
SCOPE OF VARIABLES
Global scope: the variables with such scope are visible and available in all files of a
package.

Local scope: the variables are only known within that function;

G lo
bal
sc o
Local scope
pe
Local scope

Local scope
02/28/2024
02/28/2024
CONSTANT
•A constant is a name for a fixed value.

•The value of a variable can vary, but the value of a constant must remain constant.

•Constants are declared with the const key word


Constants can’t be declared with := syntax

•Constants can be of any data type, just like a variable


QUIZ
Q1. A file containing Go code has to have what extension?

.go
Q2. Are these variables the same?

var Name = “Diana”


var name string = “Diana”
Var NAME = “Diana” No variable names are case sensitive
LASAGNA https://exercism.org/tracks/

CHALLENGE go/exercises/lasagna/edit
CHALLENGE
Implement a function which will convert Celsius to Fahrenheit. Types of
temperatures are float32 which are aliased to Celsius and Fahrenheit for you.

func toFahrenheit(t Celsius){


}
•Temperature in ˚F = (Temp in °C * 9/5) + 32

02/28/2024
TYPE CONVERSION
You can convert some data types, but not all types can be converted to each other.

•int to a float: just write it as a whole number.


•float32 / float64 to int: You can convert a floating-point number to an int by using
the int() function
•int to string: You can convert an int to a string using the strconv.Itoa()
•string to int: You can convert a string to an int using the strconv.Atoi()
•byte to string: You can convert a byte (or a slice of bytes) to a string using the
string() function.
•string to byte: You can convert a string to a byte (or a slice of bytes) using the
[]byte() function.
WEEK 3 Coding for women

02/28/2024
WHAT
WE’RE Arrays
LEARNIN
G THIS Slices
WEEK

02/28/2024
ARRAYS
An array is a sequence of elements of a specific length.

Arrays hold a set number of a group of items of the same type.


For example you might want to hold a list of numbers

When creating an array you separate an the values using commas, when printing it is
shown with elements separated by spaces.

02/28/2024
ARRAYS Here we are telling the computer the
type of the variable ‘fruit’ is an array of
length four and the element type is
string.
Creating an array variable without assigning a
value will create an array of the specified length
with the zero value of the given element type

[ ] = this is an array
4 = the array will be of length four
string = the elements of the array will be strings
{ } = the contents inside the curly brackets is the contents to put in the array

02/28/2024
ARRAYS
Using the … syntax allows the array to automatically determine the number of
elements.
So this

Is the same as this

02/28/2024
ACCESSING ARRAY VALUES
Elements in an array can be accessed by using the index of the value you want.
The index is a numerical value that starts at 0.

Index points of fruit =

02/28/2024
ACCESSING ARRAY VALUES
Multiple elements can be accessed by using creating a slice using : to tell the code
you want to look at multiple ___ index points.
The rule for this syntax is arrayName[startIndex:endIndex] where the starting
index is included but the ending index is excluded.

Lemon is at index 0 (this is included in the array slice)


Raspberry is at index 1 (this is included in the array slice)
Passion fruit is at index 2 (this is NOT included in the array slice)

02/28/2024
ACCESSING ARRAY VALUES

Lemon is at index 0 (this is included in the array slice)


Raspberry is at index 1 (this is included in the array slice)
Passion fruit is at index 2 (this is NOT included in the array slice)

lemon raspberry passion fruit cherry


0 1 2 3

02/28/2024
SLICES
Slices can be made as a subsection of an existing array or they can be declared in the
same way as arrays except no element count is given.

When made directly Go will create an array underlying array of the appropriate
length and capacity, which will change along with the slice.

Unlike arrays which have a static length slices can have variable lengths. This makes
them more flexible and powerful as the slice can grow or shrink to suit your current
needs.

02/28/2024
SLICES
There are three important functions to know when using slices
len retrieves the current number of elements in a slice (the length of a slice)
cap retrieves the number of elements the slice can hold before it must be resized (the
capacity of a slice)
append adds an element to the end of a slice

The len and cap functions can also be used on arrays however append is only for
slices as arrays cannot change their length

02/28/2024
It is important to know that is you wish to copy a slice or array you must use the
built-in copy function

Result of code:

The copy function takes the destination slice as the first argument and the source slice
as the second, and both slices must be of the same type.
The one major thing to note: the lengths of both destination and source slices do not
have to be equal. It will only copy up to the smaller number of elements. So if you
attempt to copy to an empty or nil slice, nothing will be copied.

02/28/2024
If you don’t use the copy function then both the original slice and the duplicate/sub
slice will both be changed

Result of code:

As you can see after changing an element in newNum, the corresponding element in
numbers also changed.

02/28/2024
MAPS
A map is an unordered collection of key-value pairs, where each key is unique.

02/28/2024
MAPS
To create a empty map you can use the make function, this initialises the map so it is
an empty map not a nil map.
The difference between a nil map and an empty map is how data can then be added
to them.
For a nil map data can only be added by setting the variable to a map of the same
type as specified. This will initialise it.

02/28/2024
MAPS
To create a empty map you can use the make function, this initialises the map so it is
an empty map not a nil map.
The difference between a nil map and an empty map is how data can then be added
to them.
For a nil map attempting to add data directly to the map will result in an error

02/28/2024
MAPS
To create a empty map you can use the make function, this initialises the map so it is
an empty map not a nil map.
The difference between a nil map and an empty map is how data can then be added
to them.
For an empty map a new map can be assigned to them or you can add a new value
pair directly without an error message.

02/28/2024
MAPS
Instead of numerical index points the values are accessed by their keys.
What do you think is the output of the following code:

ANSWER: 3

02/28/2024
MAPS
Any value can be accessed by specifying the associated key. A second value can be
returned to check if the key is in the map.

02/28/2024
WEEK 4
WHAT WE DID LAST WEEK
• Arrays

02/28/2024
THIS WEEK
•Slices
•Maps
•If – Else statements continued
•For loops

02/28/2024
HOMEWORK
Debbie
Yadira

02/28/2024
You can only have 1 func main
within a program

Func main(){
//your code
}

02/28/2024
02/28/2024
FLOW CONTROL
USING BOOLEAN LOGIC
•The order in which instructions are carried out
•There is more than one way your program can run depending on the data you feed it.
The computer will run a certain path depending on the data and the conditions you
have set it.
•True -> outcome1
•False -> outcome2
IF STATEMENT
•How do you decide if to eat or not?
•How do you decide if to visit the doctor or not?
•How do you know if to go to bed or not?

You ask yourself an IF statement!!


IF STATEMENTS
AND

2 paths, but we have not set an action for the 2 nd path


OR
NOT

! will negate the expression.


You can also use arithmetic operators.
ELSE
The else clause is run when if is evaluated to false.

2 paths, 2 possible actions


ELSE IF
When you want to check several statements/conditions. That’s when we use if – else.

It will always check the if statements in order


prioritise your statements
FOR LOOPS
A for loop is a type of loop that allows you to
execute a block of code repeatedly for a certain
number of times or until a certain condition is met.

In Go, a for loop is typically used when you need


to iterate over a collection of items, such as an
array or slice, or when you need to repeat a block
of code a certain number of times.
The basic for loop has three parts separated
by semicolons:
the init statement: executed before the first
iteration
the condition expression: evaluated before
every iteration
the post statement: executed at the end of
every iteration

The init statement will often be a short


variable declaration
the variables declared there are visible only
within the loop
The loop will stop iterating once the boolean
condition evaluates to false.
FOR RANGE LOOP

•index is the index of the value we are accessing.


•value is the actual value we have on each iteration.
•mydatastructure holds the data structure whose values will be accessed in the loop.

Used when you are more interested in value rather than location
The for-range loop can be used to access individual characters in a string.

terminal output
The for-range loop can be used to access individual key-value pairs in a map also
EXERCISE

• Write a Go program that checks if a


person lives in a household. If the
person lives in the household, the
program should print a message
saying “<name> lives here”
• However….If the person is named
"Daisy" she doesn’t live in the
house, the program should print a
message saying that "Daisy doesn't
live there, but can come in.
• If person is not named "Daisy" and
does not live in the house, the
program should print a message
saying "stranger danger!".
1. declare an array called household and put inside the persons you live with (you
can make it up!)

2. create a function called livesWithMe it takes in a string and returns a bool


Inside the function, create a for range loop to iterate over the elements of the array if the input name is
the same as an element in your array, it return true. Otherwise, return false.

3. inside func main()

 Create if else statements to print different messages depending on whether the person lives there, is
Daisy, or is neither.
NAVIGATING YOUR
FILE SYSTEM
learning Bash scripting and navigating the
command line is an important skill for coders,
regardless of your specific programming language.

It can help you work more faster and gain greater


control over your coding environment.

02/28/2024
02/28/2024
02/28/2024
02/28/2024
02/28/2024
02/28/2024
FILE STRUCTURE OF GO
Go programs are organized into
packages.
A package is a collection of
files in the same directory that
are compiled together.
Functions, types, variables, and
constants defined in one source
file are visible to all other
source files within the same
package.
A module is a collection of related Go packages that are released together.
You only need 1 module per project.
The module keeps your project contained and therefore exportable – it will keep tabs
on all the the packages, subdirectories, files, functions in your project.

Each module has a unique module path, which is specified in the go.mod file at the
root of the module. The go.mod file also specifies the version of the Go language
that the module is compatible with, as well as any dependencies(external
packages/libraries you imported) that the module requires.
HOMEWORK: WORD FREQUENCY
COUNTER

Objective: Write a Go program that reads a list of words and counts the frequency of
each word.
Instructions:
1.Initialize a Slice: Create a slice of strings containing a list of words. This can be either
hardcoded or taken as input from the user.

2.Count Word Frequencies with a Map: Create a map where the key is a word (string)
and the value is its frequency (int). Loop through the slice of words, and for each word, if
it's not in the map, add it with a value of 1. If it's already in the map, increment its value.

3.Output the Results: Loop through the map and print out each word and its frequency.
EXAMPLE
words := []string{"apple", "banana", "apple", "orange", "banana", "apple", "kiwi", "kiwi", "kiwi"}

apple: 3 banana: 2 orange: 1 kiwi: 3

02/28/2024
Hints:
•Use a for loop to iterate over the slice.
•Use Go's map data structure to maintain a count of each word.
•Remember that checking a key in a map that doesn't exist will return the zero value
for the map's value type. In the case of an int, this is 0.

02/28/2024
WEEK 5
02/28/2024
WHAT DID WE DO LAST
WEEK?
Flow control : if-else statements
For loops
File structure of Go
Working in VS code
HOW DOES THE WEB WORK?
WHAT WE WILL DO
oSetup a project directory which follows the Go conventions.
oStart a web server and listen for incoming HTTP requests.
oRoute requests to different handlers based on the request path.
oManage errors
oload HTML pages and use templates
oServe static files like images and CSS
STEP 1.
Lets create a fresh repository

02/28/2024
FIRST STEPS
Set up your main file

Create your module


Make sure that you’re in the root of the directory and
then run the go mod init <nameModule> command.

Create a handler folder - package handler


WHAT ARE HANDLERS?
• Think of handlers as being a bit like controllers. They’re responsible for executing your
application logic and for writing HTTP response headers and bodies.
• A handler is a function that processes incoming HTTP requests and generates the corresponding
HTTP response.
•It takes two arguments: a http.ResponseWriter object, which represents the
HTTP response that will be sent back to the client, and an *http.Request
object, which represents the HTTP request that the client made.
•The handler function reads the request data from the http.Request object,
processes it as needed, and generates the appropriate response using the
http.ResponseWriter object. The response can include headers, the body,
cookies, and other data that is sent back to the client.
Each time the server receives a new HTTP request it will pass the request on to the
server which will check the URL path (“/”) and dispatch the request to the matching
handler (func HomePage).
WHAT IS HTTP?

HTTP (Hypertext Transfer Protocol) is a protocol used to transfer data over the web.
It is the foundation of the World Wide Web, and it is used by web browsers and
servers to communicate with each other.
When you enter a URL in a web browser, the browser sends an HTTP request to the
web server hosting the requested resource (such as a web page or image).
The server then responds with an HTTP response, which includes the requested
resource (or an error message if the resource cannot be found).
To use this handler function in a web application, you need to use the
http.HandleFunc() function.

Next up, the server


http.ListenAndServe() is a function that starts a HTTP server and listens for
incoming requests on a specified network address.

When a client makes a request to the server, the default server that Go uses
(DefaultServeMux) will look for a handler function to process the request and
generate a response.
STEP 2 - DATA
We are going to create a struct to hold the data we want to post to our website.
WHAT IS A STRUCT?
structs are a collections of fields.

It is a container where you can group several types of data

For example if you create a struct for someone who has a bank account, inside you
would have fields of data relating to
- name string
-bank account number int
-account balance int
DECLARING AND INITIALIZING A
STRUCT

A struct in Go can contain one or more fields.


Each field in the struct must have a data type. You can use the type + struct keyword
to create a struct using syntax like this:
HOW TO ACCESS
A STRUCT
Access struct fields with a dot
STEP 3 – ADDING
TAGS TO STRUCT
JSON (Javascript Object Notation)

In web development, JSON is commonly used as a format for transmitting data between
a web server and a client application. It’s easily compressed, quick to transmit lots of
data and easy for humans to read and write.

For example, when a client makes a request to a web server, the server might respond
with JSON-encoded data that the client can then parse and display in a web browser or
mobile app.
JSON tags specify the names of the JSON fields that correspond to each struct field.
For example, the Go Id field has a JSON tag of "Id", it will look for the JSON field
with the name "Id".
Similarly, the Go RecipeName field has a JSON tag of "Recipe Name” which means
that Go will look for the JSON field with the name "Recipe Name".
WEEK 6
WHEN CREATING OUR PROGRAM, ONE OF THE
FIRST STEPS IS TO CREATE A MODULE. WHAT IS
THE COMMAND TO CREATE A MODULE, AND WHAT
IS A MODULE?

go mod init <name>

- lists all the external dependencies we need for the program


- which version of Go was used to make it
- route to the module therefore the program.
WHAT KIND OF DATA TYPE IS
A STRUCT?
A struct is composite data type (can hold several bits of information)

You create the fields inside your struct

We are going to create a structs to hold the data we want to post to our website.
HOW OUR WEBSITE WORKS
When a client (such as a web browser) wants to access a web page or web
application, it sends an HTTP request to the server that hosts the web page or
application. The server receives the request, and then passes the request to the
appropriate handler function, which generates a response that is sent back to the
client. The client then receives the response and renders it in the browser window.
The client-server relationship is typically based on the HTTP protocol, which is the
standard protocol used for communication between web browsers and servers.

It’s a common language, set of mutually understandable instructions


WHAT IS A SERVER
A server is a computer program (dedicating to serving files, its not used as a
workstation) that listens for incoming network requests and responds to those
requests by providing data or services.

The client, your computer will make a request to the server for a connection and for
data.
HANDLERS
Handler functions are functions that are called by servers to process incoming
requests and generate responses.
STEP 4 CREATE A GLOBAL
VARIABLE OF []STRUCT
RECIPE
We have created a container to store our recipe.

We now want to duplicate this format to store ALL of our recipes that’s why we
create a slice of recipe.
STEP 5 CREATE FUNCTION TO
‘FETCH’ DATA
HTTP.GET
The HTTP GET method is used to read (or retrieve) a representation of a resource.

In case of success, GET returns a representation in JSON

The go package http has a function Get that sends a GET request to the specified url
you want to get the information from.
http.Get(“url”)
HTTP METHODS
POST – Creates
GET – Reads
PUT – Updates
DELETE – Deletes
GET and POST are the only methods we will be using for our website.

(part of protocol)
.57 seconds
IO.READALL
io package has a function ReadAll which will take a file/some data and convert it
into a []byte. The []byte can then be edited or more easily converted into other data
types, depending on the desired outcome.
[]byte are also the required input type for a lot of functions that allow you to write
data to a specified location. Such as the next function we will use.
JSON.UNMARSHALL()
This function takes two inputs:
 A []byte which represents the data to be ‘unmarshalled’
 The location where you want the data to go.

Unmarshalling is the conversion of JSON to Go objects. In our case from JSON to


structs. The json tags on the struct help tell the unmarshall function where each bit of
data should go.
___.CLOSE

Whenever opening/reading a file


A memory leak is a failure in a
it should be closed. This is to
program to release discarded
prevent the file from taking up
memory, causing impaired
memory space unnecessarily
performance or failure.
which will cause a memory leak.
DEFER
Using the keyword defer tells the program you want the following action to happen
at the end of the code block.
Using defer ensures the code is carried out whenever the code terminates regardless
of any flow control later on.
This means that if you have a function with an if/else statement and you want a
specific action to occur at the end of the code regardless of where in the if/else the
code terminates defer will allow this to happen
STEP 6 TEST IF WE MANAGED TO FETCH
THE DATA

Run our function to see We should a loooong


what comes up on the slice contain all our
terminal! recipes
WEEK 6
WHEN CREATING OUR PROGRAM, ONE OF THE
FIRST STEPS IS TO CREATE A MODULE. WHAT IS
THE COMMAND TO CREATE A MODULE, AND WHAT
IS A MODULE?

go mod init <name>

- lists all the external dependencies we need for the program


- which version of Go was used to make it
- route to the module therefore the program.
WHAT KIND OF DATA TYPE IS
A STRUCT?
A struct is composite data type (can hold several bits of information)

You create the fields inside your struct

We are going to create a structs to hold the data we want to post to our website.
HOW OUR WEBSITE WORKS
When a client (such as a web browser) wants to access a web page or web
application, it sends an HTTP request to the server that hosts the web page or
application. The server receives the request, and then passes the request to the
appropriate handler function, which generates a response that is sent back to the
client. The client then receives the response and renders it in the browser window.
The client-server relationship is typically based on the HTTP protocol, which is the
standard protocol used for communication between web browsers and servers.

It’s a common language, set of mutually understandable instructions


WHAT IS A SERVER
A server is a computer program (dedicating to serving files, its not used as a
workstation) that listens for incoming network requests and responds to those
requests by providing data or services.

The client, your computer will make a request to the server for a connection and for
data.
HANDLERS
Handler functions are functions that are called by servers to process incoming
requests and generate responses.
STEP 4 CREATE A GLOBAL
VARIABLE OF []STRUCT
RECIPE
We have created a container to store our recipe.

We now want to duplicate this format to store ALL of our recipes that’s why we
create a slice of recipe.
STEP 5 CREATE FUNCTION TO
‘FETCH’ DATA
HTTP.GET
The HTTP GET method is used to read (or retrieve) a representation of a resource.

In case of success, GET returns a representation in JSON

The go package http has a function Get that sends a GET request to the specified url
you want to get the information from.
http.Get(“url”)
HTTP METHODS
POST – Creates
GET – Reads
PUT – Updates
DELETE – Deletes
GET and POST are the only methods we will be using for our website.

(part of protocol)
.57 seconds
IO.READALL
io package has a function ReadAll which will take a file/some data and convert it
into a []byte. The []byte can then be edited or more easily converted into other data
types, depending on the desired outcome.
[]byte are also the required input type for a lot of functions that allow you to write
data to a specified location. Such as the next function we will use.
JSON.UNMARSHALL()
This function takes two inputs:
 A []byte which represents the data to be ‘unmarshalled’
 The location where you want the data to go.

Unmarshalling is the conversion of JSON to Go objects. In our case from JSON to


structs. The json tags on the struct help tell the unmarshall function where each bit of
data should go.
___.CLOSE

Whenever opening/reading a file


A memory leak is a failure in a
it should be closed. This is to
program to release discarded
prevent the file from taking up
memory, causing impaired
memory space unnecessarily
performance or failure.
which will cause a memory leak.
DEFER
Using the keyword defer tells the program you want the following action to happen
at the end of the code block.
Using defer ensures the code is carried out whenever the code terminates regardless
of any flow control later on.
This means that if you have a function with an if/else statement and you want a
specific action to occur at the end of the code regardless of where in the if/else the
code terminates defer will allow this to happen
STEP 6 TEST IF WE MANAGED TO FETCH
THE DATA

Run our function to see We should a loooong


what comes up on the slice contain all our
terminal! recipes
WEEK 7 Templates in Go, HTML, CSS
WHAT WE DID LAST WEEK
•We created a container ([]recipe struct variable) to store all our recipe data from
JSON
•We created a function to fetch the data from the JSON and be able to use in our
HTML
QUIZ
WHAT IS A SERVER?
A server is a computer which listens for http request and serves a response
WHAT IS A STRUCT?
A data type which can hold multiple fields of data.
You can create your own specific variable type.
HOW WOULD I ACCESS THE
NAME FIELD OF THIS PERSON
STRUCT?
WHY DID WE CREATE A
PACKAGE DATA? WHY NOT
KEEP EVERYTHING IN
PACKAGE
Separation of concern
MAIN?
It is good practice to make different packages for parts of your code that have
different purposes.

Make the code reusable


Makes the code scalable
If something breaks in one package, the other packages will still work
WHY DID WE PUT
DEFER.INFO.CLOSE()
AFTER GETTING THE JSON
DATA?
WHAT IS THIS CODE DOING?
1. We are setting up a server:

with the net/http package

http.ListenAndServe(“:PortNumber”)

1.

2.

2. Create a handler function helloWorld

it will handle any requests made to “/” and the


2.
‘w’ http.ResponseWriter will serve the the response
1.
“Hello World”
TEMPLATES!
We use templates to integrate HTML with Go (as they
are 2 different languages)
HTML( HyperText Markup Language) is mark-up
language to do with how your web page and its content
looks.

Go is used for the backend functionality.

Templates allow us to load variables and perform some


functions on the HTML script.
HTML BOILERPLATE
• boilerplate code or just boilerplate are sections of code that are repeated in multiple
places with little to no variation.

• A boilerplate in HTML is a
template you will add at the start of
your project. You should add this
boilerplate to all of your HTML
pages.
WHAT IS A DOCTYPE IN HTML?
• The doctype tells the browser what version of HTML the page is written in.
WHAT IS THE HTML ROOT
ELEMENT?

• The <html> tag is the top level element of the HTML file
• The head tag and body tag are both nested inside the html tag. (in other words everything
is inside the html.)
• The ‘lang’ attribute sets the language for the page. It is good to include it for accessibility
reasons, so screen readers know how to pronounce the text.
WHAT ARE HEAD
TAGS?
• <head> tags contain metadata
• Metadata is information to be processed by machines
• It describes the data being given to the machine
• The charset metadata attribute tells the machine what character set the page uses.
• UTF-8 is the standard character encoding.
• It supports many languages and can support pages and forms in any mixture of those
languages.
• The viewport meta tag tells the machine how wide to render the page and the initial level
of zoom.

• E.g. if your device was 600px wide, the machine would know to render the web browser
to be 600px wide.
• The X-UA-Compatible meta tag specifies the document mode for Internet Explorer.
• The <title> tag is the name of the tab
• The <link> tag connects the html to a css file

(the part of the head we care about)


WHAT ARE BODY TAGS?
• The body tags contain all the visible content.
In Go, we have the template package to help handle templates.
We can use functions like Parse, ParseFile and Execute to load templates from files.

02/28/2024
INSERTING DATA INTO A TEMPLATE

In Go, Every field that you intend to be rendered within a template should be put
inside of {{}}
The dot inside {{.}} is shorthand for the current object.
If you want to access specific fields of the current object, you should
use {{.FieldName}}
RANGING OVER COMPOSITE
DATA
You can do a for loop and range over arrays/maps

{{range …}}{{end}}
WE ARE GOING TO UPGRADE
OUR SERVER
We use NewServeMux to handle our routing
Our website handles many requests (end points), having just 1 handler for “/” GET is
not enough! Our website has more functionality!
We will also use it to read our CSS files

NewServeMux!
NOW LET’S ADD CSS!
To make our page look prettier – we can add CSS

We have to link our HTML document to the CSS which will reads the HTML tags.
We have to link the HTML and the Go.
•CSS stands for Cascading Style Sheets

•CSS describes how HTML elements are to be


displayed on screen, paper, or in other media

•CSS saves a lot of work. It can control the layout of


multiple web pages all at once
How we access the static (CSS) files

Once inside the file, we


Fileserver finds the
send it to the server
location of CSS file
We’re using a form to submit information
(click on a button to get a recipe back)

<form method=“POST” action=“what will happen” class =“for CSS” />


WHAT
When <button/> clicked Button will submit form THE HTML
TAGS
We split the text using:

<header>
MEAN?
<h3> (size of header text)
<p> - paragraph
<footer>
WEEK 8 Finishing the project and final
review
WHAT WE DID LAST WEEK

We learnt what some of the HTML tags means

We used Templates to add our Go variables into our HTML


We learnt what {{.}} and {{range .VarName}} {{end}}
means
We updated our server to handle several requests
WHAT WE WILL DO THIS
WEEK

1 2 3
Create handler Create the HTML Update homepage
function for recipe for the recipe page HTML to make
pages buttons
• Routing logic for the
different recipe end
points
LET’S OPEN UP VS CODE AND
FINISH THIS!
Recipe1 Recipe2
RecipeName: “Hot Dog
RecipeName: “Chocolate Chip
Pretzels”
Cookies”
PrepTime: “30 mins (+ 1.5-2.5
PrepTime: “20 mins”
hours proving time)”
CookTime: “12-15mins”
CookTime: “15 mins"”
ServingSize: 15
ServingSize: 8
Tags: [“Chocolate”, “Cookie”]
Tags: [“Meat”, “Bread”]

Range over current object ([{recipe1},


{recipe2},etc.])
{{range .}}
New current object = Individual Recipe
{{.}} Output =
{{end}} {recipe1}

Tells the computer where to end the loop – only the code
between range and end will be repeated
Recipe1 Recipe2
RecipeName: “Hot Dog
RecipeName: “Chocolate Chip
Pretzels”
Cookies”
PrepTime: “30 mins (+ 1.5-2.5
PrepTime: “20 mins”
hours proving time)”
CookTime: “12-15mins”
CookTime: “15 mins"”
ServingSize: 15
ServingSize: 8
Tags: [“Chocolate”, “Cookie”]
Tags: [“Meat”, “Bread”]

Range over current object ([{recipe1},


{recipe2},etc.])
{{range .}}
New current object = Individual Recipe
{{.}} Output =
{{end}} {recipe2}

Tells the computer where to end the loop – only the code
between range and end will be repeated
Recipe1 Recipe2
RecipeName: “Hot Dog
RecipeName: “Chocolate Chip
Pretzels”
Cookies”
PrepTime: “30 mins (+ 1.5-2.5
PrepTime: “20 mins”
hours proving time)”
CookTime: “12-15mins”
CookTime: “15 mins"”
ServingSize: 15
ServingSize: 8
Tags: [“Chocolate”, “Cookie”]
Tags: [“Meat”, “Bread”]

Range over current object ([{recipe1},


{recipe2},etc.])
{{range .}}
New current object = Individual Recipe
{{.}} Output =
{{end}} {etc.}

Tells the computer where to end the loop – only the code
between range and end will be repeated
WHAT WILL THE OUTPUT BE
IN THE FOLLOWING CODE?
Recipe1 Recipe2
RecipeName: “Hot Dog
RecipeName: “Chocolate Chip
Pretzels”
Cookies”
PrepTime: “30 mins (+ 1.5-2.5
PrepTime: “20 mins”
hours proving time)”
CookTime: “12-15mins”
CookTime: “15 mins"”
ServingSize: 15
ServingSize: 8
Tags: [“Chocolate”, “Cookie”]
Tags: [“Meat”, “Bread”]

{{range .}}

{{.RecipeName}}
{{end}} Recipe2
Recipe1

OUTPUT: OUTPUT:
“Chocolate Chip Cookies” “Hot Dog Pretzels”
Files

Request
PC

Clients
Listen & Serve
Server Network/Internet Laptop
:8000

Response Mobile

Data
REVIEW OF WHAT YOU HAVE
LEARNT
• Variables
•Functions
•Variable types
•Arrays, slices
•If – else statements
•For loops
•How to upload work onto GitHub
• git add .
• git commit –m “a message”
• git push

•How to set up a repository in GitHub


•using VS code
THE PROCESS OF A WEBSITE
We have a backend (how it behaves) and a front end (how it looks)
1. we created a server – something that listens on a port for incoming http requests
2. we created handler functions to ‘handle’ different http requests
 It can handle different types of requests (GET) and lead to different /endpoints (pages)

3.linking the HTML and CSS to Go


 Templates {{.}}
You don’t have to memorize every function off by heart – in fact, we discourage
this!
Coding in real life is about being resourceful and knowing WHERE to find the
information

This isn’t a memory test. You understand how to chop and change code to fit the
specific needs.

Continue to do daily coding challenges – not directly related with website


design, but just to familiarise yourself with Go (using for loops, arrays, creating
simple functions ect…)

fail fail fail, make mistakes so you can learn and understand!!!
REVIEW EXAM
https://forms.gle/B9NYMnodxiJiGaYH8

You might also like