feat: add foomo docs for multiple concepts

This commit is contained in:
melaniegeraldine 2023-04-03 11:42:13 +02:00
parent fa94e3fd55
commit fe766dec41
10 changed files with 288 additions and 5 deletions

View File

@ -3,4 +3,14 @@ Title: CLI applications
position: 12
---
# CLI applications
import { GoPlayground } from '../../../src/components/GoPlayground';
# CLI applications
The following example has some modifications in order to run in the playground. The Go Playground does not allow flags to be passed so it's recommended you
copy the code, uncomment the flag validations, and try it out locally.
<GoPlayground
id="I86IczVAuvd"
proportion={16/10}
/>

View File

@ -1,7 +1,29 @@
---
Title: Context
position: 10
tags:
- Go Intermediate
---
import { GoPlayground } from '../../../src/components/GoPlayground';
# Context
https://gobyexample.com/context
The ```context``` package in go provides a way for request-scoped values to be passed between all goroutines that are involved in handling a request.
Context also provides a way to set certain rules like how long a process can run before you automatically cancel it. A common way ```context``` is used is
for handling HTTP requests. The context package defines the Context type which has the following methods:
- ```Done()```
* This returns a read-only channel which automatically closes when the context is canceled or when the context times out.
- ```Deadline()```
* This returns both a deadline, which represents the time that the context will be canceled at or closed at, as well as a boolean that tells you
if a deadline is set for this context.
- ```Err()```
* This returns an error explaining why the Done() channel was closed or nil if the Done() channel was not closed.
- ```Value(key interface{})```
* This returns the value stored for the passed key or nil if the key is not present.
<GoPlayground
id="A5CtgkZUu0-"
proportion={16/10}
/>

View File

@ -1,6 +1,8 @@
---
Title: Embed
position: 13
tags:
- Go Intermediate
---
# Embed

View File

@ -1,6 +1,149 @@
---
Title: Files
position: 14
tags:
- Go Basics
---
# Files
import { GoPlayground } from '../../../src/components/GoPlayground';
# Files
There are multiple packages we can utilize for reading files in a go program. We'll go over the most commonly used ones in this section.
These include: ```os```, ```io```, ```ioutil``` and ```bufio```. We'll go over some commonly used methods for each of these packages in this section.
## IOUtil
### Read Whole File
To read a whole file you can use the ```ReadFile``` function.
```go
// Takes a filepath as argument
// Returns a byteslice and an error
byteslice, err := ioutil.ReadFile(filepath)
```
## OS
The ```os``` package provides and interface with methods to handle files on your operating system in go.
### Open Files
To open a file using the ```os``` package, use the Open method. This method takes a filepath and returns the opened file and an error.
```go
file, err := os.Open(filepath)
```
### Reading Files
To read a file using the ```os``` package, use the ReadFile method. This method takes a filepath and returns the contents of the file in a byteslice and an error.
```go
byteslice, err := os.ReadFile(filepath)
```
### Writing Files
### Getting File Information
To get information about a file using the ```os``` package, use the Stat method. This method takes a filepath and information of the selected file and an error.
This information includes methods: Name() to get the name of the file, Size() to get the size the file in bytes, Mode() to get the mode of the file,
IsDir() to find out if it is a directory, ModTime() showing when the file was last modified, and Sys() describing the underlying data source.
```go
fileInfo, err := os.Stat(filepath)
```
## BufIO
Sometimes opening a whole file is not ideal, this is for example when you have a very large log file. All of it is going to be opened in memory.
For these cases you can buffer the IO, this can increase the speed of your application by reducing the number of system calls made.
Bufio provides ways to read by the file in batches. Commonly used methods in the bufIO package include: ```Scanner```, ```ReadSlice```,```ReadBytes``` and ```ReadLines```.
### Scanner
Breaks the data up in tokens. Open the file with the ```os``` Open function and pass the reader to the NewScanner function. This will return a pointer to a Scanner.
```go
myScanner = bufio.NewScanner(myIOReader)
```
### ReadSlice
This function returns a slice of the passed string based on the delimiter you pass it.
It will return every slice with the delimiter. To call it initialize a new reader with the specified string and pass the ReadSlice method a delimiter.
<GoPlayground
id="0ZFnnUjBk6l"
proportion={16/10}
/>
### ReadBytes
ReadBytes builds on the ReadSlice functionality and is called in a similar fashion. The difference is that ReadSlice is bound to a buffersize, if it does
not reach the delimiter within that size it will fail. ReadBytes is able to call ReadSlice multiple times which means that if you go over the buffersize
it won't encounter a problem. To demonstrate:
<GoPlayground
id="Jl9B6I1a8d-"
proportion={16/10}
/>
## Examples
### Read Lines
The following code provides a way to read lines from a file. It uses the ```os``` package to open the file and then ```bufio``` to create a scanner
that reads the file line by line.
```go
package main
import (
"fmt"
"os"
"bufio"
)
func main() {
file, err := os.Open(filepath)
if err != nil {
fmt.Println("Error:", err.Error())
return
}
defer os.Close() // Make sure to always close your resources
scanner := bufio.NewScanner(file)
for scanner.Scan() { // returns a boolean, so until the end of the file is reached this loop will run
fmt.Println(scanner.Text())
}
}
```
### Read Bytes
```go
package main
import (
"fmt"
"os"
"bufio"
"io"
)
func main() {
fileHandler, err := os.Open(filename)
if err != nil {
fmt.Println("Error:", err.Error())
return
}
defer os.Close() // Make sure to always close your resources
myBuffer := make([]byte, size) // Make a buffer with size of size
for {
readBytes, err := fileHandler.Read(buf)
if err != nil {
if err != io.EOF {
fmt.Println("Error:", err.Error())
return
}
break
}
fmt.Println(string(myBuffer[:readBytes]))
}
}
```

View File

@ -1,6 +1,8 @@
---
Title: Goroutines and Channels
position: 9
tags:
- Go Basics
---
import { GoPlayground } from '../../../src/components/GoPlayground';

View File

@ -1,6 +1,68 @@
---
Title: HTTP Client and Server
position: 12
tags:
- Go Basics
---
# HTTP Client and Server
# HTTP Client and Server
The HTTP protocol is used to communicate between Client and Server. The ```net/http``` package provides all methods needed to implement a client and
a server and the most commonly used request methods.
The most commonly used request methods are:
- GET:
* This method is used to request data from the server or specified source. Used for fetching data.
- POST:
* This method is used to send a request with data in the body to a server. Used for creating data.
- PATCH:
* This method is used to partially update an existing data entry.
- PUT:
* This method is used to entirely update an existing data entry.
## HTTP Client
The HTTP Client consumes the API, it sends a request to the HTTP Server. The following code shows an example for all the commonly used HTTP requests.
```go
// GET Requests: Pass the URL to request the data from.
// Returns a response and an error.
resp, err := http.Get("https://foomo.org")
// Post Requests: Pass the URL to post data to, specify the content type of the data,
// and pass the body containing the data of the request.
// Returns a response and an error.
resp, err := http.Post("https://foomo.org", "application/json", body)
// PATCH Requests, specify it's a PATCH request, pass the URL to request,
// and the body containing the data of the request.
// Returns a response and an error.
resp, err := http.NewRequest(http.MethodPatch, "https://foomo.org", body)
// PUT Requests, specify it's a PUT request, pass the URL to request,
// and the body containing the data of the request.
// Returns a response and an error.
resp, err := http.NewRequest(http.MethodPut, "https://foomo.org", body)
```
## HTTP Server
the HTTP Server accepts API calls from a Client. Handlers are a fundamental concept in the ```net/http``` package.
They are your way of basically telling how a request is supposed to be handled. Handler functions always take a ResponseWriter and a pointer to a Request as argument:
```go
func myHandler(w http.ResponseWriter, req *http.Request) {
...
}
```
In the main function of your server you register all the handlers implemented and serve them on a specified port:
```go
func main () {
http.HandleFunc("/myPage", myHandler) // specify the path and the handler function
http.ListenAndServe(":8000", nil) // specify the port and the router, which is the default router in this case.
}
```
### RESTful

View File

@ -1,6 +1,44 @@
---
Title: Interfaces
position: 11
tags:
- Go Basics
---
# Interfaces
import { GoPlayground } from '../../../src/components/GoPlayground';
# Interfaces
In go you can define a type using a set of methods by using the ```interface``` keyword.
```go
type instrumentSounds interface {
makeBand() string
}
```
So this is our instrumentSounds interface which calls a function makeBand.
<GoPlayground
id="p-Ut2K0Fa9f"
proportion={16/10}
/>
## The Empty Interface
An empty interface can hold values that satisfy any type. It's commonly used in code when the values types are unknown.
```go
func main() {
var myInterface interface{}
myInterface = 300
fmt.Println(myInterface)
myInterface = "Hello world"
fmt.Println(myInterface)
}
```
Even though the type is changed this program will still work fine because myInterface is an empty interface so it could be of any type.
In the latest of go the any type is supported, which is simply a type alias to the empty interface, and equivalent in all ways.

View File

@ -1,6 +1,8 @@
---
Title: Map Races
position: 7
tags:
- Go Intermediate
---
# Map Races

View File

@ -1,6 +1,8 @@
---
Title: Reflection
position: 8
tags:
- Go Intermediate
---
# Reflection