Skip to content

Commit

Permalink
day 13
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelCade committed Jan 12, 2022
1 parent b13a05b commit ec8e0a4
Show file tree
Hide file tree
Showing 17 changed files with 558 additions and 31 deletions.
29 changes: 29 additions & 0 deletions Days/Go/day13_example1.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package main

import "fmt"

func main() {

const DaysTotal int = 90
var remainingDays uint = 90
challenge := "#90DaysOfDevOps"

fmt.Printf("Welcome to the %v challenge.\nThis challenge consists of %v days\n", challenge, DaysTotal)

var TwitterName string
var DaysCompleted uint

// asking for user input
fmt.Println("Enter Your Twitter Handle: ")
fmt.Scanln(&TwitterName)

fmt.Println("How many days have you completed?: ")
fmt.Scanln(&DaysCompleted)

// calculate remaining days
remainingDays = remainingDays - DaysCompleted

fmt.Printf("Thank you %v for taking part and completing %v days.\n", TwitterName, DaysCompleted)
fmt.Printf("You have %v days remaining for the %v challenge\n", remainingDays, challenge)
fmt.Println("Good luck")
}
74 changes: 74 additions & 0 deletions Days/Go/day13_example2.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package main

import (
// other imports
"fmt"
"log"
"os"

"github.com/dghubble/go-twitter/twitter"
"github.com/dghubble/oauth1"
)

// Credentials stores all of our access/consumer tokens
// and secret keys needed for authentication against
// the twitter REST API.
type Credentials struct {
ConsumerKey string
ConsumerSecret string
AccessToken string
AccessTokenSecret string
}

// getClient is a helper function that will return a twitter client
// that we can subsequently use to send tweets, or to stream new tweets
// this will take in a pointer to a Credential struct which will contain
// everything needed to authenticate and return a pointer to a twitter Client
// or an error
func getClient(creds *Credentials) (*twitter.Client, error) {
// Pass in your consumer key (API Key) and your Consumer Secret (API Secret)
config := oauth1.NewConfig(creds.ConsumerKey, creds.ConsumerSecret)
// Pass in your Access Token and your Access Token Secret
token := oauth1.NewToken(creds.AccessToken, creds.AccessTokenSecret)

httpClient := config.Client(oauth1.NoContext, token)
client := twitter.NewClient(httpClient)

// Verify Credentials
verifyParams := &twitter.AccountVerifyParams{
SkipStatus: twitter.Bool(true),
IncludeEmail: twitter.Bool(true),
}

// we can retrieve the user and verify if the credentials
// we have used successfully allow us to log in!
user, _, err := client.Accounts.VerifyCredentials(verifyParams)
if err != nil {
return nil, err
}

log.Printf("User's ACCOUNT:\n%+v\n", user)
return client, nil
}
func main() {
fmt.Println("Go-Twitter Bot v0.01")
creds := Credentials{
AccessToken: os.Getenv("ACCESS_TOKEN"),
AccessTokenSecret: os.Getenv("ACCESS_TOKEN_SECRET"),
ConsumerKey: os.Getenv("CONSUMER_KEY"),
ConsumerSecret: os.Getenv("CONSUMER_SECRET"),
}

client, err := getClient(&creds)
if err != nil {
log.Println("Error getting Twitter Client")
log.Println(err)
}

tweet, resp, err := client.Statuses.Update("A Test Tweet from the future, testing a #90DaysOfDevOps Program that tweets, tweet tweet", nil)
if err != nil {
log.Println(err)
}
log.Printf("%+v\n", resp)
log.Printf("%+v\n", tweet)
}
99 changes: 99 additions & 0 deletions Days/Go/day13_example3.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package main

import (
// other imports
"fmt"
"log"
"os"

"github.com/dghubble/go-twitter/twitter"
"github.com/dghubble/oauth1"
)

// Credentials stores all of our access/consumer tokens
// and secret keys needed for authentication against
// the twitter REST API.
type Credentials struct {
ConsumerKey string
ConsumerSecret string
AccessToken string
AccessTokenSecret string
}

// getClient is a helper function that will return a twitter client
// that we can subsequently use to send tweets, or to stream new tweets
// this will take in a pointer to a Credential struct which will contain
// everything needed to authenticate and return a pointer to a twitter Client
// or an error
func getClient(creds *Credentials) (*twitter.Client, error) {
// Pass in your consumer key (API Key) and your Consumer Secret (API Secret)
config := oauth1.NewConfig(creds.ConsumerKey, creds.ConsumerSecret)
// Pass in your Access Token and your Access Token Secret
token := oauth1.NewToken(creds.AccessToken, creds.AccessTokenSecret)

httpClient := config.Client(oauth1.NoContext, token)
client := twitter.NewClient(httpClient)

// Verify Credentials
verifyParams := &twitter.AccountVerifyParams{
SkipStatus: twitter.Bool(true),
IncludeEmail: twitter.Bool(true),
}

// we can retrieve the user and verify if the credentials
// we have used successfully allow us to log in!
user, _, err := client.Accounts.VerifyCredentials(verifyParams)
if err != nil {
return nil, err
}

log.Printf("User's ACCOUNT:\n%+v\n", user)
return client, nil
}
func main() {
creds := Credentials{
AccessToken: os.Getenv("ACCESS_TOKEN"),
AccessTokenSecret: os.Getenv("ACCESS_TOKEN_SECRET"),
ConsumerKey: os.Getenv("CONSUMER_KEY"),
ConsumerSecret: os.Getenv("CONSUMER_SECRET"),
}
{
const DaysTotal int = 90
var remainingDays uint = 90
challenge := "#90DaysOfDevOps"

fmt.Printf("Welcome to the %v challenge.\nThis challenge consists of %v days\n", challenge, DaysTotal)

var TwitterName string
var DaysCompleted uint

// asking for user input
fmt.Println("Enter Your Twitter Handle: ")
fmt.Scanln(&TwitterName)

fmt.Println("How many days have you completed?: ")
fmt.Scanln(&DaysCompleted)

// calculate remaining days
remainingDays = remainingDays - DaysCompleted

//fmt.Printf("Thank you %v for taking part and completing %v days.\n", TwitterName, DaysCompleted)
//fmt.Printf("You have %v days remaining for the %v challenge\n", remainingDays, challenge)
// fmt.Println("Good luck")

client, err := getClient(&creds)
if err != nil {
log.Println("Error getting Twitter Client, this is expected if you did not supply your Twitter API tokens")
log.Println(err)
}

message := fmt.Sprintf("Hey I am %v I have been doing the %v for %v days and I have %v Days left", TwitterName, challenge, DaysCompleted, remainingDays)
tweet, resp, err := client.Statuses.Update(message, nil)
if err != nil {
log.Println(err)
}
log.Printf("%+v\n", resp)
log.Printf("%+v\n", tweet)
}

}
19 changes: 19 additions & 0 deletions Days/Go/makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
BINARY_NAME=90DaysOfDevOps

build:
GOARCH=amd64 GOOS=darwin go build -o ${BINARY_NAME}_0.2_darwin main.go
GOARCH=amd64 GOOS=linux go build -o ${BINARY_NAME}_0.2_linux main.go
GOARCH=amd64 GOOS=windows go build -o ${BINARY_NAME}_0.2_windows main.go
GOARCH=arm64 GOOS=linux go build -o ${BINARY_NAME}_0.2_linux_arm64 main.go
GOARCH=arm64 GOOS=darwin go build -o ${BINARY_NAME}_0.2_darwin_arm64 main.go

run:
./${BINARY_NAME}

build_and_run: build run

clean:
go clean
rm ${BINARY_NAME}-darwin
rm ${BINARY_NAME}-linux
rm ${BINARY_NAME}-windows
Binary file added Days/Images/Day13_Go1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Days/Images/Day13_Go2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Days/Images/Day13_Go3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Days/Images/Day13_Go4.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Days/Images/Day13_Go5.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Days/Images/Day13_Go6.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Days/Images/Day13_Go7.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Days/Images/Day13_Go8.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Days/Images/Day13_Go9.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
46 changes: 23 additions & 23 deletions Days/day11.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
Before we get into the topics for today I want to give a massive shout out to [Techworld with Nana](https://www.youtube.com/watch?v=yyUHQIec83I) and this fantastic concise journey through the fundamentals of Go.

On [Day8](day08.md) we set our environment up, on [Day9](day09.md) we walked through the Hello #90DaysOfDevOps code and on [Day10](day10.md)) we looked at our Go workspace and went into a little more deeper into compiling and running the code.
On [Day8](day08.md) we set our environment up, on [Day9](day09.md) we walked through the Hello #90DaysOfDevOps code and on [Day10](day10.md)) we looked at our Go workspace and went a little deeper into compiling and running the code.

Today we are going to take a look into Variables, Constants and Data Types whilst writing a new program.

## Variables & Constants in Go
Let's start by planning our application, I think it would be a good idea to work on a program that tells us how many days we have remaining in our #90DaysOfDevOps challenge.
Let's start by planning our application, I think it would be a good idea to work on a program that tells us how many days we have remained in our #90DaysOfDevOps challenge.

The first thing to consider here is that as we are building our app and we are welcoming our attendees and we are giving the user feedback on the amount of days they have completed we might use the term #90DaysOfDevOps a number of times throughout the program. This is a great use case to make #90DaysOfDevOps a variable within our program.
The first thing to consider here is that as we are building our app and we are welcoming our attendees and we are giving the user feedback on the number of days they have completed we might use the term #90DaysOfDevOps many times throughout the program. This is a great use case to make #90DaysOfDevOps a variable within our program.

- Variables are used to store values.
- Like a little box with our saved information or values.
- We can then use this variable across the program which also benefits that if this challenge or variable changes then we only have to change this in one place. Meaning we could translate this to other challenges we have in the community by just changing that one variable value.

In order to declare this in our Go Program we define a value by using a **keyword** for variables. This will live within our `func main` block of code that you will see later. You can find more about [Keywords](https://go.dev/ref/spec#Keywords)here.
To declare this in our Go Program we define a value by using a **keyword** for variables. This will live within our `func main` block of code that you will see later. You can find more about [Keywords](https://go.dev/ref/spec#Keywords)here.

Remember to make sure that your variable names are descriptive. If you declare a variable you must use it or you will get an error, this is to avoid possible dead code, code that is never used. This is the same for packages not used.

Expand All @@ -38,7 +38,7 @@ You will then see from the below that we built our code with the above example a

![](Images/Day11_Go1.png)

We also know that our challenge is 90 days at least for this challenge, but next maybe its 100 so we want to define a variable to help us here as well. However for the purpose of our program we want to define this as a constant. Constants are like variables, except that their value cannot be changed within code (we can still create a new app later on down the line with this code and change this constant but this 90 will not change whilst we are running our application)
We also know that our challenge is 90 days at least for this challenge, but next, maybe it's 100 so we want to define a variable to help us here as well. However, for our program, we want to define this as a constant. Constants are like variables, except that their value cannot be changed within code (we can still create a new app later on down the line with this code and change this constant but this 90 will not change whilst we are running our application)

Adding the `const` to our code and adding another line of code to print this.

Expand All @@ -48,11 +48,11 @@ package main
import "fmt"
func main() {
var challenge = "#90DaysOfDevOps"
const daystotal = 90
var challenge = "#90DaysOfDevOps"
const daystotal = 90
fmt.Println("Welcome to", challenge)
fmt.Println("This is a", daystotal, "challenge")
fmt.Println("Welcome to", challenge)
fmt.Println("This is a", daystotal, "challenge")
}
```
You can find the above code snippet in [day11_example2.go](Go/day11_example2.go)
Expand All @@ -61,23 +61,23 @@ If we then go through that `go build` process again and run you will see below t

![](Images/Day11_Go2.png)

Finally, and this won't be the end of our program we will come back to this in [Day12](day12.md) to add more functionality. We now want to add another variable for the number of days we have completed of the challenge.
Finally, and this won't be the end of our program we will come back to this in [Day12](day12.md) to add more functionality. We now want to add another variable for the number of days we have completed the challenge.

Below I added `dayscomplete` variable with the amount of days completed.
Below I added `dayscomplete` variable with the number of days completed.

```
package main
import "fmt"
func main() {
var challenge = "#90DaysOfDevOps"
const daystotal = 90
var dayscomplete = 11
var challenge = "#90DaysOfDevOps"
const daystotal = 90
var dayscomplete = 11
fmt.Println("Welcome to", challenge, "")
fmt.Println("This is a", daystotal, "challenge and you have completed", dayscomplete, "days")
fmt.Println("Great work")
fmt.Println("Welcome to", challenge, "")
fmt.Println("This is a", daystotal, "challenge and you have completed", dayscomplete, "days")
fmt.Println("Great work")
}
```
You can find the above code snippet in [day11_example3.go](Go/day11_example3.go)
Expand All @@ -94,16 +94,16 @@ Variables may also be defined in a simpler format in your code. Instead of defin

```
func main() {
challenge := "#90DaysOfDevOps"
const daystotal = 90
challenge := "#90DaysOfDevOps"
const daystotal = 90
```

## Data Types
In the above examples we have not defined the type of variables, this is because we can give it a value here and Go is smart enough to know what that type is or at least can infer what it is based on the value you have stored. However if we want user input this will require a specific type.
In the above examples, we have not defined the type of variables, this is because we can give it a value here and Go is smart enough to know what that type is or at least can infer what it is based on the value you have stored. However, if we want a user to input this will require a specific type.

We have used Strings and Integers in our code so far. Integers for the number of days and strings are for the name of the challenge.

It is also important to note that each data type can do different things and behaves differently. For example integers can multiply where as strings do not.
It is also important to note that each data type can do different things and behaves differently. For example, integers can multiply where strings do not.

There are four categories

Expand All @@ -112,14 +112,14 @@ There are four categories
- **Reference type**: Pointers, slices, maps, functions, and channels come under this category.
- **Interface type**

Data type is an important concept in programming. Data type specifies the size and type of variable values.
The data type is an important concept in programming. Data type specifies the size and type of variable values.

Go is statically typed, meaning that once a variable type is defined, it can only store data of that type.

Go has three basic data types:

- **bool**: represents a boolean value and is either true or false
- **Numeric**: represents integer types, floating point values, and complex types
- **Numeric**: represents integer types, floating-point values, and complex types
- **string**: represents a string value

I found this resource super detailed on data types [Golang by example](https://golangbyexample.com/all-data-types-in-golang-with-examples/)
Expand Down
14 changes: 7 additions & 7 deletions Days/day12.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
## Getting user input with Pointers and a finished program

Yesterday ([Day 11](day11.md)), we created our first Go program that was self contained and the parts we wanted to really get user input for were created as variables within our code and given values, we now want to ask the user for their input to give the variable the value for the end message.
Yesterday ([Day 11](day11.md)), we created our first Go program that was self-contained and the parts we wanted to get user input for were created as variables within our code and given values, we now want to ask the user for their input to give the variable the value for the end message.

## Getting user input

Expand All @@ -12,9 +12,9 @@ Let's now add a new variable called `TwitterName` you can find this new code at

![](Images/Day12_Go1.png)

We are on day 12 and we would need to change that `dayscomplete` every day and compile our code each day if this was hard coded which doesn't sound so great.
We are on day 12 and we would need to change that `dayscomplete` every day and compile our code each day if this was hardcoded which doesn't sound so great.

Getting user input, we want to get the value of maybe a name and the amount of days completed. For us to do this we can use another function from within the `fmt` package.
Getting user input, we want to get the value of maybe a name and the number of days completed. For us to do this we can use another function from within the `fmt` package.

Recap on the `fmt` package, different functions for: formatted input and output (I/O)

Expand All @@ -37,7 +37,7 @@ Let's now run our program and you see we have input for both of the above.

Ok, that's great we got some user input and we printed a message but what about getting our program to tell us how many days we have left in our challenge.

In order for us to do that we have created a variable called `remainingDays` and we have hard valued this in our code as `90` we then need to change the value of this value to print out the remaining days when we get our user input of `DaysCompleted` we can do this with this simple variable change.
For us to do that we have created a variable called `remainingDays` and we have hard valued this in our code as `90` we then need to change the value of this value to print out the remaining days when we get our user input of `DaysCompleted` we can do this with this simple variable change.

```
remainingDays = remainingDays - DaysCompleted
Expand All @@ -48,14 +48,13 @@ If we now run this program you can see that simple calculation is made based on

![](Images/Day12_Go3.png)


## What is a pointer? (Special Variables)

A pointer is a (special) variable that points to the memory address of another variable.

A great explanation of this can be found here at [geeksforgeeks](https://www.geeksforgeeks.org/pointers-in-golang/)

Let's simplify our code now and show with and without the `&` in front of one of our print commands,this gives us the memory address of the pointer. I have added this code example here. [day12_example4.go](Go/day12_example4.go)
Let's simplify our code now and show with and without the `&` in front of one of our print commands, this gives us the memory address of the pointer. I have added this code example here. [day12_example4.go](Go/day12_example4.go)

Below is running this code.

Expand All @@ -71,4 +70,5 @@ Below is running this code.
- [FreeCodeCamp - Learn Go Programming - Golang Tutorial for Beginners](https://www.youtube.com/watch?v=YS4e4q9oBaU&t=1025s)
- [Hitesh Choudhary - Complete playlist](https://www.youtube.com/playlist?list=PLRAV69dS1uWSR89FRQGZ6q9BR2b44Tr9N)

See you on [Day 13](day13.md).
See you on [Day 13](day13.md).

Loading

0 comments on commit ec8e0a4

Please sign in to comment.