├── arrayslicemap
├── appendcopy
│ └── appendcopy.go
├── array
│ └── array.go
├── arrayinterno
│ └── arrayinterno.go
├── forrange
│ └── forrange.go
├── map1
│ └── map.go
├── map2
│ └── map.go
├── mapaninhado
│ └── mapaninhado.go
├── slice
│ └── slice.go
└── slicemake
│ └── slicemake.go
├── concorrencia
├── bloqueio
│ └── bloqueio.go
├── buffer
│ └── buffer.go
├── channel1
│ └── channel.go
├── channel2
│ └── channel.go
├── cpus
│ └── cpus.go
├── generator
│ └── generator.go
├── goroutine
│ └── goroutine.go
├── multiplexar
│ └── multiplexar.go
├── multiplexar2
│ └── multiplexar.go
├── primos
│ └── primos.go
└── select
│ └── select.go
├── controles
├── desafioswitch
│ └── desafio.go
├── for
│ └── for.go
├── ifelse
│ └── ifelse.go
├── ifelseif
│ └── ifelseif.go
├── ifinit
│ └── ifinit.go
├── switch1
│ └── switch.go
├── switch2
│ └── switch.go
└── switch3
│ └── switch.go
├── funcoes
├── basicas
│ └── basicas.go
├── closure
│ └── closure.go
├── comoparametro
│ └── comoparametro.go
├── defer
│ └── defer.go
├── init
│ ├── init.go
│ └── init2.go
├── pilha
│ └── pilha.go
├── ponteiro
│ └── ponteiro.go
├── primeiraclasse
│ └── primeiraclasse.go
├── recursividade
│ └── recursividade.go
├── recursividade_simples
│ └── recursividade.go
├── retornonomeado
│ └── retornonomeado.go
├── variatica
│ └── variatica.go
└── variaticaslice
│ └── variaticaslice.go
├── fundamentos
├── aritmeticos
│ └── aritmeticos.go
├── atribuicao
│ └── atribuicao.go
├── comandos
│ ├── comandos
│ └── comandos.go
├── constvar
│ └── constvar.go
├── conversoes
│ └── conversoes.go
├── funcoes
│ ├── funcoes.go
│ └── main.go
├── logicos
│ └── logicos.go
├── naoternario
│ └── naoternario.go
├── ponteiro
│ └── ponteiro.go
├── primeiro
│ └── primeiro.go
├── prints
│ └── prints.go
├── relacionais
│ └── relacionais.go
├── tipos
│ └── tipos.go
├── unario
│ └── unario.go
└── zeros
│ └── zeros.go
├── http
├── dinamico
│ └── dinamico.go
├── serverdb
│ ├── cliente.go
│ └── server.go
└── static
│ ├── public
│ └── index.html
│ └── static.go
├── pacote
├── reta
│ ├── main.go
│ └── reta.go
├── reuso
│ └── main.go
└── usandolib
│ └── usandolib.go
├── sql
├── estrutura
│ └── estrutura.go
├── insert
│ └── insert.go
├── select
│ └── select.go
├── transacao
│ └── transacao.go
└── update
│ └── update.go
├── testes
├── arquitetura
│ └── arquitetura_test.go
├── matematica
│ ├── matematica.go
│ └── matematica_test.go
└── tabela
│ └── strings_test.go
└── tipos
├── composicao
└── composicao.go
├── interface1
└── interface.go
├── interface2
└── interface.go
├── json
└── json.go
├── metodos
└── metodos.go
├── meutipo
└── meutipo.go
├── pseudoheranca
└── pseudoheranca.go
├── struct
└── struct.go
├── structaninhada
└── structaninhada.go
└── tipointerface
└── tipointerface.go
/arrayslicemap/appendcopy/appendcopy.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | array1 := [3]int{1, 2, 3}
7 | var slice1 []int
8 |
9 | // array1 = append(array1, 4, 5, 6)
10 | slice1 = append(slice1, 4, 5, 6)
11 | fmt.Println(array1, slice1)
12 |
13 | slice2 := make([]int, 2)
14 | copy(slice2, slice1)
15 | fmt.Println(slice2)
16 | }
17 |
--------------------------------------------------------------------------------
/arrayslicemap/array/array.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | // homogênea (mesmo tipo) e estática (fixo)
7 | var notas [3]float64
8 | fmt.Println(notas)
9 |
10 | notas[0], notas[1], notas[2] = 7.8, 4.3, 9.1
11 | // notas[3] = 10
12 | fmt.Println(notas)
13 |
14 | total := 0.0
15 | for i := 0; i < len(notas); i++ {
16 | total += notas[i]
17 | }
18 |
19 | media := total / float64(len(notas))
20 | fmt.Printf("Média %.2f\n", media)
21 | }
22 |
--------------------------------------------------------------------------------
/arrayslicemap/arrayinterno/arrayinterno.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | s1 := make([]int, 10, 20)
7 | s2 := append(s1, 1, 2, 3)
8 | fmt.Println(s1, s2)
9 |
10 | s1[0] = 7
11 | fmt.Println(s1, s2)
12 | }
13 |
--------------------------------------------------------------------------------
/arrayslicemap/forrange/forrange.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | numeros := [...]int{1, 2, 3, 4, 5} // compilador conta!
7 |
8 | for i, numero := range numeros {
9 | fmt.Printf("%d) %d\n", i+1, numero)
10 | }
11 |
12 | for _, num := range numeros {
13 | fmt.Println(num)
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/arrayslicemap/map1/map.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | // var aprovados map[int]string
7 | // mapas devem ser inicializados
8 | aprovados := make(map[int]string)
9 |
10 | aprovados[12345678978] = "Maria"
11 | aprovados[98765432100] = "Pedro"
12 | aprovados[95135745682] = "Ana"
13 | fmt.Println(aprovados)
14 |
15 | for cpf, nome := range aprovados {
16 | fmt.Printf("%s (CPF: %d)\n", nome, cpf)
17 | }
18 |
19 | fmt.Println(aprovados[95135745682])
20 | delete(aprovados, 95135745682)
21 | fmt.Println(aprovados[95135745682])
22 | }
23 |
--------------------------------------------------------------------------------
/arrayslicemap/map2/map.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | funcsESalarios := map[string]float64{
7 | "José João": 11325.45,
8 | "Gabriela Silva": 15456.78,
9 | "Pedro Junior": 1200.0,
10 | }
11 |
12 | funcsESalarios["Rafael Filho"] = 1350.0
13 | delete(funcsESalarios, "Inexistente")
14 |
15 | for nome, salario := range funcsESalarios {
16 | fmt.Println(nome, salario)
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/arrayslicemap/mapaninhado/mapaninhado.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | funcsPorLetra := map[string]map[string]float64{
7 | "G": {
8 | "Gabriela Silva": 15456.78,
9 | "Guga Pereira": 8456.78,
10 | },
11 | "J": {
12 | "José João": 11325.45,
13 | },
14 | "P": {
15 | "Pedro Junior": 1200.0,
16 | },
17 | }
18 |
19 | delete(funcsPorLetra, "P")
20 |
21 | for letra, funcs := range funcsPorLetra {
22 | fmt.Println(letra, funcs)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/arrayslicemap/slice/slice.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "reflect"
6 | )
7 |
8 | func main() {
9 | a1 := [3]int{1, 2, 3} // array
10 | s1 := []int{1, 2, 3} // slice
11 | fmt.Println(a1, s1)
12 | fmt.Println(reflect.TypeOf(a1), reflect.TypeOf(s1))
13 |
14 | a2 := [5]int{1, 2, 3, 4, 5}
15 |
16 | // Slice não é um array! Slide define um pedaço de um array.
17 | s2 := a2[1:3]
18 | fmt.Println(a2, s2)
19 |
20 | s3 := a2[:2] // novo slice, mas aponta para o mesmo array
21 | fmt.Println(a2, s3)
22 |
23 | // vc pode imaginar um slice como: tamanho e um ponteiro para um elemento de um array
24 | s4 := s2[:1]
25 | fmt.Println(s2, s4)
26 | }
27 |
--------------------------------------------------------------------------------
/arrayslicemap/slicemake/slicemake.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | s := make([]int, 10)
7 | s[9] = 12
8 | fmt.Println(s)
9 |
10 | s = make([]int, 10, 20)
11 | fmt.Println(s, len(s), cap(s))
12 |
13 | s = append(s, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
14 | fmt.Println(s, len(s), cap(s))
15 |
16 | s = append(s, 1)
17 | fmt.Println(s, len(s), cap(s))
18 | }
19 |
--------------------------------------------------------------------------------
/concorrencia/bloqueio/bloqueio.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func rotina(c chan int) {
9 | time.Sleep(time.Second)
10 | c <- 1 // operação bloqueante
11 | fmt.Println("Só depois que foi lido")
12 | }
13 |
14 | func main() {
15 | c := make(chan int) // canal sem buffer
16 |
17 | go rotina(c)
18 |
19 | fmt.Println(<-c) // operação bloqueante
20 | fmt.Println("Foi lido")
21 | fmt.Println(<-c) // deadlock
22 | fmt.Println("Fim")
23 | }
24 |
--------------------------------------------------------------------------------
/concorrencia/buffer/buffer.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func rotina(ch chan int) {
9 | ch <- 1
10 | ch <- 2
11 | ch <- 3
12 | ch <- 4
13 | ch <- 5
14 | fmt.Println("Executou!")
15 | ch <- 6
16 | }
17 |
18 | func main() {
19 | ch := make(chan int, 3)
20 | go rotina(ch)
21 |
22 | time.Sleep(time.Second)
23 | fmt.Println(<-ch)
24 | }
25 |
--------------------------------------------------------------------------------
/concorrencia/channel1/channel.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | ch := make(chan int, 1)
7 |
8 | ch <- 1 // enviando dados para o canal (escrita)
9 | <-ch // recebendo dados do canal (leitura)
10 |
11 | ch <- 2
12 | fmt.Println(<-ch)
13 | }
14 |
--------------------------------------------------------------------------------
/concorrencia/channel2/channel.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | // Channel (canal) - é a forma de comunicação entre goroutines
9 | // channel é um tipo
10 |
11 | func doisTresQuatroVezes(base int, c chan int) {
12 | time.Sleep(time.Second)
13 | c <- 2 * base // enviando dados para o canal
14 |
15 | time.Sleep(time.Second)
16 | c <- 3 * base
17 |
18 | time.Sleep(3 * time.Second)
19 | c <- 4 * base
20 | }
21 |
22 | func main() {
23 | c := make(chan int)
24 | go doisTresQuatroVezes(2, c)
25 |
26 | a, b := <-c, <-c // recebendo dados do canal
27 | fmt.Println(a, b)
28 |
29 | fmt.Println(<-c)
30 | }
31 |
--------------------------------------------------------------------------------
/concorrencia/cpus/cpus.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "runtime"
6 | )
7 |
8 | func main() {
9 | fmt.Println(runtime.NumCPU())
10 | }
11 |
--------------------------------------------------------------------------------
/concorrencia/generator/generator.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "io/ioutil"
6 | "net/http"
7 | "regexp"
8 | )
9 |
10 | // Google I/O 2012 - Go Concurrency Patterns
11 |
12 | // <-chan - canal somente-leitura
13 | func titulo(urls ...string) <-chan string {
14 | c := make(chan string)
15 | for _, url := range urls {
16 | go func(url string) {
17 | resp, _ := http.Get(url)
18 | html, _ := ioutil.ReadAll(resp.Body)
19 |
20 | r, _ := regexp.Compile("
(.*?)<\\/title>")
21 | c <- r.FindStringSubmatch(string(html))[1]
22 | }(url)
23 | }
24 | return c
25 | }
26 |
27 | func main() {
28 | t1 := titulo("https://www.cod3r.com.br", "https://www.google.com")
29 | t2 := titulo("https://www.amazon.com", "https://www.youtube.com")
30 | fmt.Println("Primeiros:", <-t1, "|", <-t2)
31 | fmt.Println("Segundos:", <-t1, "|", <-t2)
32 | }
33 |
--------------------------------------------------------------------------------
/concorrencia/goroutine/goroutine.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func fale(pessoa, texto string, qtde int) {
9 | for i := 0; i < qtde; i++ {
10 | time.Sleep(time.Second)
11 | fmt.Printf("%s: %s (iteração %d)\n", pessoa, texto, i+1)
12 | }
13 | }
14 |
15 | func main() {
16 | // fale("Maria", "Pq vc não fala comigo?", 3)
17 | // fale("João", "Só posso falar depois de vc!", 1)
18 |
19 | // go fale("Maria", "Ei...", 500)
20 | // go fale("João", "Opa...", 500)
21 |
22 | go fale("Maria", "Entendi!!!", 10)
23 | fale("João", "Parabéns!", 5)
24 | }
25 |
--------------------------------------------------------------------------------
/concorrencia/multiplexar/multiplexar.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/cod3rcursos/html"
7 | )
8 |
9 | func encaminhar(origem <-chan string, destino chan string) {
10 | for {
11 | destino <- <-origem
12 | }
13 | }
14 |
15 | // multiplexar - misturar (mensagens) num canal
16 | func juntar(entrada1, entrada2 <-chan string) <-chan string {
17 | c := make(chan string)
18 | go encaminhar(entrada1, c)
19 | go encaminhar(entrada2, c)
20 | return c
21 | }
22 |
23 | func main() {
24 | c := juntar(
25 | html.Titulo("https://www.cod3r.com.br", "https://www.google.com"),
26 | html.Titulo("https://www.amazon.com", "https://www.youtube.com"),
27 | )
28 | fmt.Println(<-c, "|", <-c)
29 | fmt.Println(<-c, "|", <-c)
30 | }
31 |
--------------------------------------------------------------------------------
/concorrencia/multiplexar2/multiplexar.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func falar(pessoa string) <-chan string {
9 | c := make(chan string)
10 | go func() {
11 | for i := 0; i < 3; i++ {
12 | time.Sleep(time.Second)
13 | c <- fmt.Sprintf("%s falando: %d", pessoa, i)
14 | }
15 | }()
16 | return c
17 | }
18 |
19 | func juntar(entrada1, entrada2 <-chan string) <-chan string {
20 | c := make(chan string)
21 | go func() {
22 | for {
23 | select {
24 | case s := <-entrada1:
25 | c <- s
26 | case s := <-entrada2:
27 | c <- s
28 | }
29 | }
30 | }()
31 | return c
32 | }
33 |
34 | func main() {
35 | c := juntar(falar("João"), falar("Maria"))
36 | fmt.Println(<-c, <-c)
37 | fmt.Println(<-c, <-c)
38 | fmt.Println(<-c, <-c)
39 | }
40 |
--------------------------------------------------------------------------------
/concorrencia/primos/primos.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func isPrimo(num int) bool {
9 | for i := 2; i < num; i++ {
10 | if num%i == 0 {
11 | return false
12 | }
13 | }
14 | return true
15 | }
16 |
17 | func primos(n int, c chan int) {
18 | inicio := 2
19 | for i := 0; i < n; i++ {
20 | for primo := inicio; ; primo++ {
21 | if isPrimo(primo) {
22 | c <- primo
23 | inicio = primo + 1
24 | time.Sleep(time.Millisecond * 180)
25 | break
26 | }
27 | }
28 | }
29 | close(c)
30 | }
31 |
32 | func main() {
33 | c := make(chan int, 30)
34 | go primos(60, c)
35 | for primo := range c {
36 | fmt.Printf("%d ", primo)
37 | }
38 | fmt.Println("Fim!")
39 | }
40 |
--------------------------------------------------------------------------------
/concorrencia/select/select.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 |
7 | "github.com/cod3rcursos/html"
8 | )
9 |
10 | func oMaisRapido(url1, url2, url3 string) string {
11 | c1 := html.Titulo(url1)
12 | c2 := html.Titulo(url2)
13 | c3 := html.Titulo(url3)
14 |
15 | // estrutura de controle específica para concorrência
16 | select {
17 | case t1 := <-c1:
18 | return t1
19 | case t2 := <-c2:
20 | return t2
21 | case t3 := <-c3:
22 | return t3
23 | case <-time.After(1000 * time.Millisecond):
24 | return "Todos perderam!"
25 | // default:
26 | // return "Sem resposta ainda!"
27 | }
28 | }
29 |
30 | func main() {
31 | campeao := oMaisRapido(
32 | "https://www.youtube.com",
33 | "https://www.amazon.com",
34 | "https://www.google.com",
35 | )
36 | fmt.Println(campeao)
37 | }
38 |
--------------------------------------------------------------------------------
/controles/desafioswitch/desafio.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func notaParaConceito(n float64) string {
6 | switch {
7 | case n >= 9 && n <= 10:
8 | return "A"
9 | case n >= 8 && n < 9:
10 | return "B"
11 | case n >= 5 && n < 8:
12 | return "C"
13 | case n >= 3 && n < 5:
14 | return "D"
15 | default:
16 | return "E"
17 | }
18 | }
19 |
20 | func main() {
21 | fmt.Println(notaParaConceito(9.8))
22 | fmt.Println(notaParaConceito(6.9))
23 | fmt.Println(notaParaConceito(2.1))
24 | }
25 |
--------------------------------------------------------------------------------
/controles/for/for.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func main() {
9 |
10 | i := 1
11 | for i <= 10 { // não tem while em Go
12 | fmt.Println(i)
13 | i++
14 | }
15 |
16 | for i := 0; i <= 20; i += 2 {
17 | fmt.Printf("%d ", i)
18 | }
19 |
20 | fmt.Println("\nMisturando... ")
21 | for i := 1; i <= 10; i++ {
22 | if i%2 == 0 {
23 | fmt.Print("Par ")
24 | } else {
25 | fmt.Print("Impar ")
26 | }
27 | }
28 |
29 | for {
30 | // laço infinito
31 | fmt.Println("Para sempre...")
32 | time.Sleep(time.Second)
33 | }
34 |
35 | // Veremos o foreach no capítulo de array
36 | }
37 |
--------------------------------------------------------------------------------
/controles/ifelse/ifelse.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func imprimirResultado(nota float64) {
6 | if nota >= 7 {
7 | fmt.Println("Aprovado com nota", nota)
8 | } else {
9 | fmt.Println("Reprovado com nota", nota)
10 | }
11 | }
12 |
13 | func main() {
14 | imprimirResultado(7.3)
15 | imprimirResultado(5.1)
16 | }
17 |
--------------------------------------------------------------------------------
/controles/ifelseif/ifelseif.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func notaParaConceito(n float64) string {
6 | if n >= 9 && n <= 10 {
7 | return "A"
8 | } else if n >= 8 && n < 9 {
9 | return "B"
10 | } else if n >= 5 && n < 8 {
11 | return "C"
12 | } else if n >= 3 && n < 5 {
13 | return "D"
14 | } else {
15 | return "E"
16 | }
17 | }
18 |
19 | func main() {
20 | fmt.Println(notaParaConceito(9.8))
21 | fmt.Println(notaParaConceito(6.9))
22 | fmt.Println(notaParaConceito(2.1))
23 | }
24 |
--------------------------------------------------------------------------------
/controles/ifinit/ifinit.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "math/rand"
6 | "time"
7 | )
8 |
9 | func numeroAleatorio() int {
10 | s := rand.NewSource(time.Now().UnixNano())
11 | r := rand.New(s)
12 | return r.Intn(10)
13 | }
14 |
15 | func main() {
16 | if i := numeroAleatorio(); i > 5 { // tb suportado no switch
17 | fmt.Println("Ganhou!!!")
18 | } else {
19 | fmt.Println("Perdeu!")
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/controles/switch1/switch.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func notaParaConceito(n float64) string {
6 | var nota = int(n)
7 | switch nota {
8 | case 10:
9 | fallthrough
10 | case 9:
11 | return "A"
12 | case 8, 7:
13 | return "B"
14 | case 6, 5:
15 | return "C"
16 | case 4, 3:
17 | return "D"
18 | case 2, 1, 0:
19 | return "E"
20 | default:
21 | return "Nota inválida"
22 | }
23 | }
24 |
25 | func main() {
26 | fmt.Println(notaParaConceito(9.8))
27 | fmt.Println(notaParaConceito(6.9))
28 | fmt.Println(notaParaConceito(2.1))
29 | }
30 |
--------------------------------------------------------------------------------
/controles/switch2/switch.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func main() {
9 | t := time.Now()
10 | switch { // switch true
11 | case t.Hour() < 12:
12 | fmt.Println("Bom dia!")
13 | case t.Hour() < 18:
14 | fmt.Println("Boa tarde.")
15 | default:
16 | fmt.Println("Boa noite.")
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/controles/switch3/switch.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func tipo(i interface{}) string {
9 | switch i.(type) {
10 | case int:
11 | return "inteiro"
12 | case float32, float64:
13 | return "real"
14 | case string:
15 | return "string"
16 | case func():
17 | return "função"
18 | default:
19 | return "não sei"
20 | }
21 | }
22 |
23 | func main() {
24 | fmt.Println(tipo(2.3))
25 | fmt.Println(tipo(1))
26 | fmt.Println(tipo("Opa"))
27 | fmt.Println(tipo(func() {}))
28 | fmt.Println(tipo(time.Now()))
29 | }
30 |
--------------------------------------------------------------------------------
/funcoes/basicas/basicas.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func f1() {
6 | fmt.Println("F1")
7 | }
8 |
9 | func f2(p1 string, p2 string) {
10 | fmt.Printf("F2: %s %s\n", p1, p2)
11 | }
12 |
13 | func f3() string {
14 | return "F3"
15 | }
16 |
17 | func f4(p1, p2 string) string {
18 | return fmt.Sprintf("F4: %s %s", p1, p2)
19 | }
20 |
21 | func f5() (string, string) {
22 | return "Retorno 1", "Retorno 2"
23 | }
24 |
25 | func main() {
26 | f1()
27 | f2("Param1", "Param2")
28 |
29 | r3, r4 := f3(), f4("Param1", "Param2")
30 | fmt.Println(r3)
31 | fmt.Println(r4)
32 |
33 | r51, r52 := f5()
34 | fmt.Println("F5:", r51, r52)
35 | }
36 |
--------------------------------------------------------------------------------
/funcoes/closure/closure.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func closure() func() {
6 | x := 10
7 | var funcao = func() {
8 | fmt.Println(x)
9 | }
10 | return funcao
11 | }
12 |
13 | func main() {
14 | x := 20
15 | fmt.Println(x)
16 |
17 | imprimeX := closure()
18 | imprimeX()
19 | }
20 |
--------------------------------------------------------------------------------
/funcoes/comoparametro/comoparametro.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func multiplicacao(a, b int) int {
6 | return a * b
7 | }
8 |
9 | func exec(funcao func(int, int) int, p1, p2 int) int {
10 | return funcao(p1, p2)
11 | }
12 |
13 | func main() {
14 | resultado := exec(multiplicacao, 3, 4)
15 | fmt.Println(resultado)
16 | }
17 |
--------------------------------------------------------------------------------
/funcoes/defer/defer.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func obterValorAprovado(numero int) int {
6 | defer fmt.Println("fim!")
7 | if numero > 5000 {
8 | fmt.Println("Valor alto...")
9 | return 5000
10 | }
11 | fmt.Println("Valor baixo...")
12 | return numero
13 | }
14 |
15 | func main() {
16 | fmt.Println(obterValorAprovado(6000))
17 | fmt.Println(obterValorAprovado(3000))
18 | }
19 |
--------------------------------------------------------------------------------
/funcoes/init/init.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func init() {
6 | fmt.Println("Inicializando...")
7 | }
8 |
9 | func main() {
10 | fmt.Println("Main...")
11 | }
12 |
--------------------------------------------------------------------------------
/funcoes/init/init2.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func init() {
6 | fmt.Println("Inicializando2...")
7 | }
8 |
--------------------------------------------------------------------------------
/funcoes/pilha/pilha.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "runtime/debug"
4 |
5 | func f3() {
6 | debug.PrintStack()
7 | }
8 |
9 | func f2() {
10 | f3()
11 | }
12 |
13 | func f1() {
14 | f2()
15 | }
16 |
17 | func main() {
18 | f1()
19 | }
20 |
--------------------------------------------------------------------------------
/funcoes/ponteiro/ponteiro.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func inc1(n int) {
6 | n++ // n = n + 1
7 | }
8 |
9 | // revisão: um ponteiro é representado por um *
10 | func inc2(n *int) {
11 | // revisão: * é usado para desreferenciar, ou seja,
12 | // ter acesso ao valor no qual o ponteiro aponta
13 | *n++
14 | }
15 |
16 | func main() {
17 | n := 1
18 |
19 | inc1(n) // por valor
20 | fmt.Println(n)
21 |
22 | // revisão: & usado para obter o endereço da variável
23 | inc2(&n) // por referência
24 | fmt.Println(n)
25 | }
26 |
--------------------------------------------------------------------------------
/funcoes/primeiraclasse/primeiraclasse.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | var soma = func(a, b int) int {
6 | return a + b
7 | }
8 |
9 | func main() {
10 | fmt.Println(soma(2, 3))
11 |
12 | sub := func(a, b int) int {
13 | return a - b
14 | }
15 |
16 | fmt.Println(sub(2, 3))
17 | }
18 |
--------------------------------------------------------------------------------
/funcoes/recursividade/recursividade.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func fatorial(n int) (int, error) {
6 | switch {
7 | case n < 0:
8 | return -1, fmt.Errorf("número inválido: %d", n)
9 | case n == 0:
10 | return 1, nil
11 | default:
12 | fatorialAnterior, _ := fatorial(n - 1)
13 | return n * fatorialAnterior, nil
14 | }
15 | }
16 |
17 | func main() {
18 | resultado, _ := fatorial(5)
19 | fmt.Println(resultado)
20 |
21 | _, err := fatorial(-4)
22 | if err != nil {
23 | fmt.Println(err)
24 | }
25 |
26 | // Uma solução melhor seria... uint!
27 | }
28 |
--------------------------------------------------------------------------------
/funcoes/recursividade_simples/recursividade.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func fatorial(n uint) uint {
6 | switch {
7 | case n == 0:
8 | return 1
9 | default:
10 | return n * fatorial(n-1)
11 | }
12 | }
13 |
14 | func main() {
15 | resultado := fatorial(5)
16 | fmt.Println(resultado)
17 | }
18 |
--------------------------------------------------------------------------------
/funcoes/retornonomeado/retornonomeado.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func trocar(p1, p2 int) (segundo, primeiro int) {
6 | segundo = p2
7 | primeiro = p1
8 | return // retorno limpo
9 | }
10 |
11 | func main() {
12 | x, y := trocar(2, 3)
13 | fmt.Println(x, y)
14 |
15 | segundo, primeiro := trocar(7, 1)
16 | fmt.Println(segundo, primeiro)
17 | }
18 |
--------------------------------------------------------------------------------
/funcoes/variatica/variatica.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func media(numeros ...float64) float64 {
6 | total := 0.0
7 | for _, num := range numeros {
8 | total += num
9 | }
10 | return total / float64(len(numeros))
11 | }
12 |
13 | func main() {
14 | fmt.Printf("Média: %.2f", media(7.7, 8.1, 5.9, 9.9))
15 | }
16 |
--------------------------------------------------------------------------------
/funcoes/variaticaslice/variaticaslice.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func imprimirAprovados(aprovados ...string) {
6 | fmt.Println("Lista de Aprovados")
7 | for i, aprovado := range aprovados {
8 | fmt.Printf("%d) %s\n", i+1, aprovado)
9 | }
10 | }
11 |
12 | func main() {
13 | aprovados := []string{"Maria", "Pedro", "Rafael", "Guilherme"}
14 | imprimirAprovados(aprovados...)
15 | }
16 |
--------------------------------------------------------------------------------
/fundamentos/aritmeticos/aritmeticos.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "math"
6 | )
7 |
8 | func main() {
9 | a := 3
10 | b := 2
11 |
12 | fmt.Println("Soma =>", a+b)
13 | fmt.Println("Subtração =>", a-b)
14 | fmt.Println("Divisão =>", a/b)
15 | fmt.Println("Multiplicação =>", a*b)
16 | fmt.Println("Módulo =>", a%b)
17 |
18 | // bitwise
19 | fmt.Println("E =>", a&b) // 11 & 10 = 10
20 | fmt.Println("Ou =>", a|b) // 11 | 10 = 11
21 | fmt.Println("Xor =>", a^b) // 11 ^ 10 = 01
22 |
23 | c := 3.0
24 | d := 2.0
25 |
26 | // outras operacoes usando math...
27 | fmt.Println("Maior =>", math.Max(float64(a), float64(b)))
28 | fmt.Println("Menor =>", math.Min(c, d))
29 | fmt.Println("Exponenciação =>", math.Pow(c, d))
30 | }
31 |
--------------------------------------------------------------------------------
/fundamentos/atribuicao/atribuicao.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | var b byte = 3
7 | fmt.Println(b)
8 |
9 | i := 3 // inferência de tipo
10 | i += 3 // i = i + 3
11 | i -= 3 // i = i - 3
12 | i /= 2 // i = i / 2
13 | i *= 2 // i = i * 2
14 | i %= 2 // i = i % 2
15 |
16 | fmt.Println(i)
17 |
18 | x, y := 1, 2
19 | fmt.Println(x, y)
20 |
21 | x, y = y, x
22 | fmt.Println(x, y)
23 | }
24 |
--------------------------------------------------------------------------------
/fundamentos/comandos/comandos:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cod3rcursos/curso-go/7738b521d0c96aa319ef5ccedbe2e033f08dad7f/fundamentos/comandos/comandos
--------------------------------------------------------------------------------
/fundamentos/comandos/comandos.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | fmt.Printf("Outro programa em %s!!!!\n", "Go")
7 | }
8 |
--------------------------------------------------------------------------------
/fundamentos/constvar/constvar.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | m "math"
6 | )
7 |
8 | func main() {
9 | const PI float64 = 3.1415
10 | var raio = 3.2 // tipo (float64) inferido pelo compilador
11 |
12 | // forma reduzida de criar uma var
13 | area := PI * m.Pow(raio, 2)
14 | fmt.Println("A área da circunferência é", area)
15 |
16 | const (
17 | a = 1
18 | b = 2
19 | )
20 |
21 | var (
22 | c = 3
23 | d = 4
24 | )
25 |
26 | fmt.Println(a, b, c, d)
27 |
28 | var e, f bool = true, false
29 | fmt.Println(e, f)
30 |
31 | g, h, i := 2, false, "epa!"
32 | fmt.Println(g, h, i)
33 | }
34 |
--------------------------------------------------------------------------------
/fundamentos/conversoes/conversoes.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "strconv"
6 | )
7 |
8 | func main() {
9 | x := 2.4
10 | y := 2
11 | fmt.Println(x / float64(y))
12 |
13 | nota := 6.9
14 | notaFinal := int(nota)
15 | fmt.Println(notaFinal)
16 |
17 | // cuidado...
18 | fmt.Println("Teste " + string(97))
19 |
20 | // int para string
21 | fmt.Println("Teste " + strconv.Itoa(123))
22 |
23 | // string para int
24 | num, _ := strconv.Atoi("123")
25 | fmt.Println(num - 122)
26 |
27 | b, _ := strconv.ParseBool("true")
28 | if b {
29 | fmt.Println("Verdadeiro")
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/fundamentos/funcoes/funcoes.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func somar(a int, b int) int {
6 | return a + b
7 | }
8 |
9 | func imprimir(valor int) {
10 | fmt.Println(valor)
11 | }
12 |
--------------------------------------------------------------------------------
/fundamentos/funcoes/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | func main() {
4 | resultado := somar(3, 4)
5 | imprimir(resultado)
6 | }
7 |
--------------------------------------------------------------------------------
/fundamentos/logicos/logicos.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func compras(trab1, trab2 bool) (bool, bool, bool) {
6 | comprarTv50 := trab1 && trab2
7 | comprarTv32 := trab1 != trab2 // ou exclusivo
8 | comprarSorvete := trab1 || trab2
9 |
10 | return comprarTv50, comprarTv32, comprarSorvete
11 | }
12 |
13 | func main() {
14 | tv50, tv32, sorvete := compras(true, true)
15 | fmt.Printf("Tv50: %t, Tv32: %t, Sorvete: %t, Saudável: %t",
16 | tv50, tv32, sorvete, !sorvete)
17 | }
18 |
--------------------------------------------------------------------------------
/fundamentos/naoternario/naoternario.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | // Não tem operador ternário
6 | func obterResultado(nota float64) string {
7 | // return nota >= 6 ? "Aprovado" : "Reprovado"
8 | if nota >= 6 {
9 | return "Aprovado"
10 | }
11 | return "Reprovado"
12 | }
13 |
14 | func main() {
15 | fmt.Println(obterResultado(6.2))
16 | }
17 |
--------------------------------------------------------------------------------
/fundamentos/ponteiro/ponteiro.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | i := 1
7 |
8 | var p *int = nil
9 | p = &i // pegando o endereço da variável
10 | *p++ // desreferenciando (pegando o valor)
11 | i++
12 |
13 | // Go não tem aritmética de ponteiros
14 | // p++
15 |
16 | fmt.Println(p, *p, i, &i)
17 | }
18 |
--------------------------------------------------------------------------------
/fundamentos/primeiro/primeiro.go:
--------------------------------------------------------------------------------
1 | // Programas executáveis iniciam pelo pacote main
2 | package main
3 |
4 | /*
5 | Os códigos em Go são organizados em pacotes
6 | e para usá-los é necessário declarar um ou vários imports
7 | */
8 | import "fmt"
9 |
10 | // A porta de entrada de um programa Go é a função main
11 | func main() {
12 | fmt.Print("Primeiro ")
13 | fmt.Print("Programa!")
14 |
15 | /*
16 | Sobre comentários...
17 |
18 | 1) Priorize código legível e faça comentários que agrega valor!
19 | 2) Evite comentários óbvios
20 | 3) Durante o curso abuse dos comentários
21 | */
22 | }
23 |
--------------------------------------------------------------------------------
/fundamentos/prints/prints.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | fmt.Print("Mesma")
7 | fmt.Print(" linha.")
8 |
9 | fmt.Println(" Nova")
10 | fmt.Println("linha.")
11 |
12 | x := 3.141516
13 |
14 | // fmt.Println("O valor de x é " + x)
15 | xs := fmt.Sprint(x)
16 | fmt.Println("O valor de x é " + xs)
17 | fmt.Println("O valor de x é", x)
18 |
19 | fmt.Printf("O valor de x é %.2f.", x)
20 |
21 | a := 1
22 | b := 1.9999
23 | c := false
24 | d := "opa"
25 | fmt.Printf("\n%d %f %.1f %t %s", a, b, b, c, d)
26 | fmt.Printf("\n%v %v %v %v", a, b, c, d)
27 | }
28 |
--------------------------------------------------------------------------------
/fundamentos/relacionais/relacionais.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func main() {
9 | fmt.Println("Strings:", "Banana" == "Banana")
10 | fmt.Println("!=", 3 != 2)
11 | fmt.Println("<", 3 < 2)
12 | fmt.Println(">", 3 > 2)
13 | fmt.Println("<=", 3 <= 2)
14 | fmt.Println(">=", 3 >= 2)
15 |
16 | d1 := time.Unix(0, 0)
17 | d2 := time.Unix(0, 0)
18 |
19 | fmt.Println("Datas:", d1 == d2)
20 | fmt.Println("Datas:", d1.Equal(d2))
21 |
22 | type Pessoa struct {
23 | Nome string
24 | }
25 |
26 | p1 := Pessoa{"João"}
27 | p2 := Pessoa{"João"}
28 | fmt.Println("Pessoas:", p1 == p2)
29 | }
30 |
--------------------------------------------------------------------------------
/fundamentos/tipos/tipos.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "math"
6 | "reflect"
7 | )
8 |
9 | func main() {
10 | // números inteiros
11 | fmt.Println(1, 2, 1000)
12 | fmt.Println("Literal inteiro é", reflect.TypeOf(32000))
13 |
14 | // sem sinal (só positivos)... uint8 uint16 uint32 uint64
15 | var b byte = 255
16 | fmt.Println("O byte é", reflect.TypeOf(b))
17 |
18 | // com sinal... int8 int16 int32 int64
19 | i1 := math.MaxInt64
20 | fmt.Println("O valor máximo do int é", i1)
21 | fmt.Println("O tipo de i1 é", reflect.TypeOf(i1))
22 |
23 | var i2 rune = 'a' // representa um mapeamento da tabela Unicode (int32)
24 | fmt.Println("O rune é", reflect.TypeOf(i2))
25 | fmt.Println(i2)
26 |
27 | // números reais (float32, float64)
28 | var x float32 = 49.99
29 | fmt.Println("O tipo de x é", reflect.TypeOf(x))
30 | fmt.Println("O tipo do literal 49.99 é", reflect.TypeOf(49.99)) // float64
31 |
32 | // boolean
33 | bo := true
34 | fmt.Println("O tipo de bo é", reflect.TypeOf(bo))
35 | fmt.Println(!bo)
36 |
37 | // string
38 | s1 := "Olá meu nome é Leo"
39 | fmt.Println(s1 + "!")
40 | fmt.Println("O tamanho da string é", len(s1))
41 |
42 | // string com multiplas linhas
43 | s2 := `Olá
44 | meu
45 | nome
46 | é
47 | Leo`
48 | fmt.Println("O tamanho da string é", len(s2))
49 |
50 | // char???
51 | // var x char = 'b'
52 | char := 'a'
53 | fmt.Println("O tipo de char é", reflect.TypeOf(char))
54 | fmt.Println(char)
55 | }
56 |
--------------------------------------------------------------------------------
/fundamentos/unario/unario.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | x := 1
7 | y := 2
8 |
9 | // apenas postfix
10 | x++ // x += 1 ou x = x + 1
11 | fmt.Println(x)
12 |
13 | y-- // y -= 1 ou y = y - 1
14 | fmt.Println(y)
15 |
16 | // fmt.Println(x == y--)
17 | }
18 |
--------------------------------------------------------------------------------
/fundamentos/zeros/zeros.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | var a int
7 | var b float64
8 | var c bool
9 | var d string
10 | var e *int
11 |
12 | fmt.Printf("%v %v %v %q %v", a, b, c, d, e)
13 | }
14 |
--------------------------------------------------------------------------------
/http/dinamico/dinamico.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "log"
6 | "net/http"
7 | "time"
8 | )
9 |
10 | func horaCerta(w http.ResponseWriter, r *http.Request) {
11 | s := time.Now().Format("02/01/2006 03:04:05")
12 | fmt.Fprintf(w, "Hora certa: %s", s)
13 | }
14 |
15 | func main() {
16 | http.HandleFunc("/horaCerta", horaCerta)
17 | log.Println("Executando...")
18 | log.Fatal(http.ListenAndServe(":3000", nil))
19 | }
20 |
--------------------------------------------------------------------------------
/http/serverdb/cliente.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "database/sql"
5 | "encoding/json"
6 | "fmt"
7 | "log"
8 | "net/http"
9 | "strconv"
10 | "strings"
11 |
12 | _ "github.com/go-sql-driver/mysql"
13 | )
14 |
15 | // Usuario :)
16 | type Usuario struct {
17 | ID int `json:"id"`
18 | Nome string `json:"nome"`
19 | }
20 |
21 | // UsuarioHandler analisa o request e delega para função adequada
22 | func UsuarioHandler(w http.ResponseWriter, r *http.Request) {
23 | sid := strings.TrimPrefix(r.URL.Path, "/usuarios/")
24 | id, _ := strconv.Atoi(sid)
25 |
26 | switch {
27 | case r.Method == "GET" && id > 0:
28 | usuarioPorID(w, r, id)
29 | case r.Method == "GET":
30 | usuarioTodos(w, r)
31 | default:
32 | w.WriteHeader(http.StatusNotFound)
33 | fmt.Fprintf(w, "Desculpa... :(")
34 | }
35 | }
36 |
37 | func usuarioPorID(w http.ResponseWriter, r *http.Request, id int) {
38 | db, err := sql.Open("mysql", "root:123456@/cursogo")
39 | if err != nil {
40 | log.Fatal(err)
41 | }
42 | defer db.Close()
43 |
44 | var u Usuario
45 | db.QueryRow("select id, nome from usuarios where id = ?", id).Scan(&u.ID, &u.Nome)
46 |
47 | json, _ := json.Marshal(u)
48 |
49 | w.Header().Set("Content-Type", "application/json")
50 | fmt.Fprint(w, string(json))
51 | }
52 |
53 | func usuarioTodos(w http.ResponseWriter, r *http.Request) {
54 | db, err := sql.Open("mysql", "root:123456@/cursogo")
55 | if err != nil {
56 | log.Fatal(err)
57 | }
58 | defer db.Close()
59 |
60 | rows, _ := db.Query("select id, nome from usuarios")
61 | defer rows.Close()
62 |
63 | var usuarios []Usuario
64 | for rows.Next() {
65 | var usuario Usuario
66 | rows.Scan(&usuario.ID, &usuario.Nome)
67 | usuarios = append(usuarios, usuario)
68 | }
69 |
70 | json, _ := json.Marshal(usuarios)
71 |
72 | w.Header().Set("Content-Type", "application/json")
73 | fmt.Fprint(w, string(json))
74 | }
75 |
--------------------------------------------------------------------------------
/http/serverdb/server.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "log"
5 | "net/http"
6 | )
7 |
8 | func main() {
9 | http.HandleFunc("/usuarios/", UsuarioHandler)
10 | log.Println("Executando...")
11 | log.Fatal(http.ListenAndServe(":3000", nil))
12 | }
13 |
--------------------------------------------------------------------------------
/http/static/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Página usando Go
8 |
9 |
10 | Go!!!!
11 |
12 |
--------------------------------------------------------------------------------
/http/static/static.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "log"
5 | "net/http"
6 | )
7 |
8 | func main() {
9 | fs := http.FileServer(http.Dir("public"))
10 | http.Handle("/", fs)
11 |
12 | log.Println("Executando...")
13 | log.Fatal(http.ListenAndServe(":3000", nil))
14 | }
15 |
--------------------------------------------------------------------------------
/pacote/reta/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | p1 := Ponto{2.0, 2.0}
7 | p2 := Ponto{2.0, 4.0}
8 |
9 | fmt.Println(catetos(p1, p2))
10 | fmt.Println(Distancia(p1, p2))
11 | }
12 |
--------------------------------------------------------------------------------
/pacote/reta/reta.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "math"
4 |
5 | // Iniciando com letra maiúscula é PÚBLICO (visivel dentro e fora do pacote)!
6 | // Iniciando com letra minúscula é PRIVADO (visivel apenas dentro do pacote)!
7 |
8 | // Por exemplo...
9 | // Ponto - gerará algo público
10 | // ponto ou _Ponto - gerará algo privado
11 |
12 | // Ponto representa uma coordenada no plano cartesiano
13 | type Ponto struct {
14 | x float64
15 | y float64
16 | }
17 |
18 | func catetos(a, b Ponto) (cx, cy float64) {
19 | cx = math.Abs(b.x - a.x)
20 | cy = math.Abs(b.y - a.y)
21 | return
22 | }
23 |
24 | // Distancia é reponsável por calcular a distância linear entre dois pontos
25 | func Distancia(a, b Ponto) float64 {
26 | cx, cy := catetos(a, b)
27 | return math.Sqrt(math.Pow(cx, 2) + math.Pow(cy, 2))
28 | }
29 |
--------------------------------------------------------------------------------
/pacote/reuso/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/cod3rcursos/area"
7 | )
8 |
9 | func main() {
10 | fmt.Println(area.Circ(6.0))
11 | fmt.Println(area.Rect(5.0, 2.0))
12 | // fmt.Println(area._TrianguloEq(5.0, 2.0))
13 | }
14 |
--------------------------------------------------------------------------------
/pacote/usandolib/usandolib.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "github.com/cod3rcursos/goarea"
4 | import "fmt"
5 |
6 | func main() {
7 | fmt.Println(goarea.Circ(4.0))
8 | }
9 |
--------------------------------------------------------------------------------
/sql/estrutura/estrutura.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "database/sql"
5 |
6 | _ "github.com/go-sql-driver/mysql"
7 | )
8 |
9 | func exec(db *sql.DB, sql string) sql.Result {
10 | result, err := db.Exec(sql)
11 | if err != nil {
12 | panic(err)
13 | }
14 | return result
15 | }
16 |
17 | func main() {
18 | db, err := sql.Open("mysql", "root:123456@/")
19 | if err != nil {
20 | panic(err)
21 | }
22 | defer db.Close()
23 |
24 | exec(db, "create database if not exists cursogo")
25 | exec(db, "use cursogo")
26 | exec(db, "drop table if exists usuarios")
27 | exec(db, `create table usuarios (
28 | id integer auto_increment,
29 | nome varchar(80),
30 | PRIMARY KEY (id)
31 | )`)
32 | }
33 |
--------------------------------------------------------------------------------
/sql/insert/insert.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "database/sql"
5 | "fmt"
6 |
7 | _ "github.com/go-sql-driver/mysql"
8 | )
9 |
10 | func main() {
11 | db, err := sql.Open("mysql", "root:123456@/cursogo")
12 | if err != nil {
13 | panic(err)
14 | }
15 | defer db.Close()
16 |
17 | stmt, _ := db.Prepare("insert into usuarios(nome) values(?)")
18 | stmt.Exec("Maria")
19 | stmt.Exec("João")
20 |
21 | res, _ := stmt.Exec("Pedro")
22 |
23 | id, _ := res.LastInsertId()
24 | fmt.Println(id)
25 |
26 | linhas, _ := res.RowsAffected()
27 | fmt.Println(linhas)
28 | }
29 |
--------------------------------------------------------------------------------
/sql/select/select.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "database/sql"
5 | "fmt"
6 | "log"
7 |
8 | _ "github.com/go-sql-driver/mysql"
9 | )
10 |
11 | type usuario struct {
12 | id int
13 | nome string
14 | }
15 |
16 | func main() {
17 | db, err := sql.Open("mysql", "root:123456@/cursogo")
18 | if err != nil {
19 | log.Fatal(err)
20 | }
21 | defer db.Close()
22 |
23 | rows, _ := db.Query("select id, nome from usuarios where id > ?", 3)
24 | defer rows.Close()
25 |
26 | for rows.Next() {
27 | var u usuario
28 | rows.Scan(&u.id, &u.nome)
29 | fmt.Println(u)
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/sql/transacao/transacao.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "database/sql"
5 | "log"
6 |
7 | _ "github.com/go-sql-driver/mysql"
8 | )
9 |
10 | func main() {
11 | db, err := sql.Open("mysql", "root:123456@/cursogo")
12 | if err != nil {
13 | log.Fatal(err)
14 | }
15 | defer db.Close()
16 |
17 | tx, _ := db.Begin()
18 | stmt, _ := tx.Prepare("insert into usuarios(id, nome) values(?,?)")
19 |
20 | stmt.Exec(4000, "Bia")
21 | stmt.Exec(4001, "Carlos")
22 | _, err = stmt.Exec(1, "Tiago") // chave duplicada
23 |
24 | if err != nil {
25 | tx.Rollback()
26 | log.Fatal(err)
27 | }
28 |
29 | tx.Commit()
30 | }
31 |
--------------------------------------------------------------------------------
/sql/update/update.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "database/sql"
5 | "log"
6 |
7 | _ "github.com/go-sql-driver/mysql"
8 | )
9 |
10 | func main() {
11 | db, err := sql.Open("mysql", "root:123456@/cursogo")
12 | if err != nil {
13 | log.Fatal(err)
14 | }
15 | defer db.Close()
16 |
17 | // update
18 | stmt, _ := db.Prepare("update usuarios set nome = ? where id = ?")
19 | stmt.Exec("Uóxiton Istive", 1)
20 | stmt.Exec("Sheristone Uasleska", 2)
21 |
22 | // delete
23 | stmt2, _ := db.Prepare("delete from usuarios where id = ?")
24 | stmt2.Exec(3)
25 | }
26 |
--------------------------------------------------------------------------------
/testes/arquitetura/arquitetura_test.go:
--------------------------------------------------------------------------------
1 | package arquitetura
2 |
3 | import (
4 | "runtime"
5 | "testing"
6 | )
7 |
8 | func TestDependente(t *testing.T) {
9 | t.Parallel()
10 | if runtime.GOARCH == "amd64" {
11 | t.Skip("Não funciona em arquitetura amd64")
12 | }
13 | // ...
14 | t.Fail()
15 | }
16 |
--------------------------------------------------------------------------------
/testes/matematica/matematica.go:
--------------------------------------------------------------------------------
1 | package matematica
2 |
3 | import (
4 | "fmt"
5 | "strconv"
6 | )
7 |
8 | // Media é responsável por calcular o que você já sabe... :)
9 | func Media(numeros ...float64) float64 {
10 | total := 0.0
11 | for _, num := range numeros {
12 | total += num
13 | }
14 | media := total / float64(len(numeros))
15 | mediaArredondada, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", media), 64)
16 | return mediaArredondada
17 | }
18 |
--------------------------------------------------------------------------------
/testes/matematica/matematica_test.go:
--------------------------------------------------------------------------------
1 | package matematica
2 |
3 | import "testing"
4 |
5 | const erroPadrao = "Valor esperado %v, mas o resultado encontrado foi %v."
6 |
7 | func TestMedia(t *testing.T) {
8 | t.Parallel()
9 | valorEsperado := 7.28
10 | valor := Media(7.2, 9.9, 6.1, 5.9)
11 |
12 | if valor != valorEsperado {
13 | t.Errorf(erroPadrao, valorEsperado, valor)
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/testes/tabela/strings_test.go:
--------------------------------------------------------------------------------
1 | package strings
2 |
3 | import (
4 | "strings"
5 | "testing"
6 | )
7 |
8 | const msgIndex = "%s (parte: %s) - índices: esperado (%d) <> encontrado (%d)."
9 |
10 | func TestIndex(t *testing.T) {
11 | t.Parallel()
12 | testes := []struct {
13 | texto string
14 | parte string
15 | esperado int
16 | }{
17 | {"Cod3r é show", "Cod3r", 0},
18 | {"", "", 0},
19 | {"Opa", "opa", -1},
20 | {"leonardo", "o", 2},
21 | }
22 |
23 | for _, teste := range testes {
24 | t.Logf("Massa: %v", teste)
25 | atual := strings.Index(teste.texto, teste.parte)
26 |
27 | if atual != teste.esperado {
28 | t.Errorf(msgIndex, teste.texto, teste.parte, teste.esperado, atual)
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/tipos/composicao/composicao.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | type esportivo interface {
6 | ligarTurbo()
7 | }
8 |
9 | type luxuoso interface {
10 | fazerBaliza()
11 | }
12 |
13 | type esportivoLuxuoso interface {
14 | esportivo
15 | luxuoso
16 | // pode adicionar mais métodos
17 | }
18 |
19 | type bwm7 struct{}
20 |
21 | func (b bwm7) ligarTurbo() {
22 | fmt.Println("Turbo...")
23 | }
24 |
25 | func (b bwm7) fazerBaliza() {
26 | fmt.Println("Baliza...")
27 | }
28 |
29 | func main() {
30 | var b esportivoLuxuoso = bwm7{}
31 | b.ligarTurbo()
32 | b.fazerBaliza()
33 | }
34 |
--------------------------------------------------------------------------------
/tipos/interface1/interface.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | type imprimivel interface {
6 | toString() string
7 | }
8 |
9 | type pessoa struct {
10 | nome string
11 | sobrenome string
12 | }
13 |
14 | type produto struct {
15 | nome string
16 | preco float64
17 | }
18 |
19 | // interfaces são implementadas implicitamente
20 | func (p pessoa) toString() string {
21 | return p.nome + " " + p.sobrenome
22 | }
23 |
24 | func (p produto) toString() string {
25 | return fmt.Sprintf("%s - R$ %.2f", p.nome, p.preco)
26 | }
27 |
28 | func imprimir(x imprimivel) {
29 | fmt.Println(x.toString())
30 | }
31 |
32 | func main() {
33 | var coisa imprimivel = pessoa{"Roberto", "Silva"}
34 | fmt.Println(coisa.toString())
35 | imprimir(coisa)
36 |
37 | coisa = produto{"Calça Jeans", 79.90}
38 | fmt.Println(coisa.toString())
39 | imprimir(coisa)
40 |
41 | p2 := produto{"Calça Jeans", 179.90}
42 | imprimir(p2)
43 | }
44 |
--------------------------------------------------------------------------------
/tipos/interface2/interface.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | type esportivo interface {
6 | ligarTurbo()
7 | }
8 |
9 | type ferrari struct {
10 | modelo string
11 | turboLigado bool
12 | velocidadeAtual int
13 | }
14 |
15 | func (f *ferrari) ligarTurbo() {
16 | f.turboLigado = true
17 | }
18 |
19 | func main() {
20 | carro1 := ferrari{"F40", false, 0}
21 | carro1.ligarTurbo()
22 |
23 | var carro2 esportivo = &ferrari{"F40", false, 0}
24 | carro2.ligarTurbo()
25 |
26 | fmt.Println(carro1, carro2)
27 | }
28 |
--------------------------------------------------------------------------------
/tipos/json/json.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | )
7 |
8 | type produto struct {
9 | ID int `json:"id"`
10 | Nome string `json:"nome"`
11 | Preco float64 `json:"preco"`
12 | Tags []string `json:"tags"`
13 | }
14 |
15 | func main() {
16 | // struct para json
17 | p1 := produto{1, "Notebook", 1899.90, []string{"Promoção", "Eletrônico"}}
18 | p1Json, _ := json.Marshal(p1)
19 | fmt.Println(string(p1Json))
20 |
21 | // json para struct
22 | var p2 produto
23 | jsonString := `{"id":2,"nome":"Caneta","preco":8.90,"tags":["Papelaria","Importado"]}`
24 | json.Unmarshal([]byte(jsonString), &p2)
25 | fmt.Println(p2.Tags[1])
26 | }
27 |
--------------------------------------------------------------------------------
/tipos/metodos/metodos.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "strings"
6 | )
7 |
8 | type pessoa struct {
9 | nome string
10 | sobrenome string
11 | }
12 |
13 | func (p pessoa) getNomeCompleto() string {
14 | return p.nome + " " + p.sobrenome
15 | }
16 |
17 | func (p *pessoa) setNomeCompleto(nomeCompleto string) {
18 | partes := strings.Split(nomeCompleto, " ")
19 | p.nome = partes[0]
20 | p.sobrenome = partes[1]
21 | }
22 |
23 | func main() {
24 | p1 := pessoa{"Pedro", "Silva"}
25 | fmt.Println(p1.getNomeCompleto())
26 |
27 | p1.setNomeCompleto("Maria Pereira")
28 | fmt.Println(p1.getNomeCompleto())
29 | }
30 |
--------------------------------------------------------------------------------
/tipos/meutipo/meutipo.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | type nota float64
6 |
7 | func (n nota) entre(inicio, fim float64) bool {
8 | return float64(n) >= inicio && float64(n) <= fim
9 | }
10 |
11 | func notaParaConceito(n nota) string {
12 | if n.entre(9.0, 10.0) {
13 | return "A"
14 | } else if n.entre(7.0, 8.99) {
15 | return "B"
16 | } else if n.entre(5.0, 7.99) {
17 | return "C"
18 | } else if n.entre(3.0, 4.99) {
19 | return "D"
20 | } else {
21 | return "E"
22 | }
23 | }
24 |
25 | func main() {
26 | fmt.Println(notaParaConceito(9.8))
27 | fmt.Println(notaParaConceito(6.9))
28 | fmt.Println(notaParaConceito(2.1))
29 | }
30 |
--------------------------------------------------------------------------------
/tipos/pseudoheranca/pseudoheranca.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | type carro struct {
6 | nome string
7 | velocidadeAtual int
8 | }
9 |
10 | type ferrari struct {
11 | carro // campos anonimos
12 | turboLigado bool
13 | }
14 |
15 | func main() {
16 | f := ferrari{}
17 | f.nome = "F40"
18 | f.velocidadeAtual = 0
19 | f.turboLigado = true
20 |
21 | fmt.Printf("A ferrari %s está com turbo ligado? %v\n", f.nome, f.turboLigado)
22 | fmt.Println(f)
23 | }
24 |
--------------------------------------------------------------------------------
/tipos/struct/struct.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | type produto struct {
6 | nome string
7 | preco float64
8 | desconto float64
9 | }
10 |
11 | // Método: função com receiver (receptor)
12 | func (p produto) precoComDesconto() float64 {
13 | return p.preco * (1 - p.desconto)
14 | }
15 |
16 | func main() {
17 | var produto1 produto
18 | produto1 = produto{
19 | nome: "Lapis",
20 | preco: 1.79,
21 | desconto: 0.05,
22 | }
23 | fmt.Println(produto1, produto1.precoComDesconto())
24 |
25 | produto2 := produto{"Notebook", 1989.90, 0.10}
26 | fmt.Println(produto2.precoComDesconto())
27 | }
28 |
--------------------------------------------------------------------------------
/tipos/structaninhada/structaninhada.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | type item struct {
6 | produtoID int
7 | qtde int
8 | preco float64
9 | }
10 |
11 | type pedido struct {
12 | userID int
13 | itens []item
14 | }
15 |
16 | func (p pedido) valorTotal() float64 {
17 | total := 0.0
18 | for _, item := range p.itens {
19 | total += item.preco * float64(item.qtde)
20 | }
21 | return total
22 | }
23 |
24 | func main() {
25 | pedido := pedido{
26 | userID: 1,
27 | itens: []item{
28 | item{produtoID: 1, qtde: 2, preco: 12.10},
29 | item{2, 1, 23.49},
30 | item{11, 100, 3.13},
31 | },
32 | }
33 |
34 | fmt.Printf("Valor total do pedido é R$ %.2f", pedido.valorTotal())
35 | }
36 |
--------------------------------------------------------------------------------
/tipos/tipointerface/tipointerface.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | type curso struct {
6 | nome string
7 | }
8 |
9 | func main() {
10 | var coisa interface{}
11 | fmt.Println(coisa)
12 |
13 | coisa = 3
14 | fmt.Println(coisa)
15 |
16 | type dinamico interface{}
17 |
18 | var coisa2 dinamico = "Opa"
19 | fmt.Println(coisa2)
20 |
21 | coisa2 = true
22 | fmt.Println(coisa2)
23 |
24 | coisa2 = curso{"Golang: Explorando a Linguagem do Google"}
25 | fmt.Println(coisa2)
26 | }
27 |
--------------------------------------------------------------------------------