The context type in Golang carries deadlines, cancelation signals, and other request-scoped values across API boundaries and between system processes
Here's a simple example
ctx := context.Background()
context.WithCancel(ctx)
#!/usr/bin/python | |
import dns.resolver | |
import dns.zone # XFR (Transfer zone requests) TCP53 | |
import dns.name # domain lookup | |
import dns.reversename # reverse DNS lookup | |
def print_records(data, type): | |
print("*" * 10) | |
print("Record %s" % type.upper()) |
package main | |
import ( | |
"io/ioutil" | |
"net/http" | |
"net/url" | |
"bytes" | |
"fmt" | |
"log" | |
) |
package main | |
import ( | |
"io/ioutil" | |
"net/http" | |
"fmt" | |
"log" | |
) | |
func main() { |
package main | |
import ( | |
"github.com/gorilla/mux" | |
"net/http" | |
"fmt" | |
) | |
func main() { | |
// new mux router |
package main | |
import ( | |
"io/ioutil" | |
"net/http" | |
"strings" | |
"fmt" | |
"log" | |
) |
Both mechanisms are meant for concurrent programming. How to work with concurrency in Go.
When you run a program in Golang, automatically generates a Go-routine, this is the engine that executes code. The go
keyword in keywords runs this function into a new Go-routine, in a general manner, some sort of parallelism is made, it avoids blocking calls.
Things change when there's only one CPU. The Go Scheduler
can execute many Go-routines but actually runs one routine at a time until it's finished or makes a blocking call, so that 'parallelism' is not fully presented.
If your server has many CPUs, each thread will run on each logical core. However, by default, Go tries to use One core.
package main | |
import ( | |
"fmt" | |
) | |
func main() { | |
// byte slice = computer friendly representation of a string | |
str := []byte("Hello slice") | |
fmt.Println(str) |
At a certain moment, when working with Golang we mentally start thinking about classes and methods, just the regular OOP way of working.
In the OOP approach, a Struct
data type can be seen as a Class definition, the Blueprint
for incoming objects, where, variables or even arrays can be seen as attributes and some functions can be seen as methods.
But that's not all correct.
The ideal scenario here is that we need a way to extending a base type to add some extra functionality. By base types, I'm referring to strings, integers, arrays, maps, and so on. Any custom method that can be appliable to an instance, we can 'associate' it to an OOP object.
package main | |
import "fmt" | |
// Map | |
func main() { | |
// statically type [key]values{} | |
colors := map[string]string{ | |
"red": "#ff0000", |