├── .gitignore ├── README.md ├── animals └── main.go ├── challenges ├── arithmetic │ ├── main.go │ └── main_test.go ├── capitalize │ ├── capitalize.go │ └── capitalize_test.go ├── find-a-string │ ├── find.go │ └── find_test.go ├── loops │ ├── loops.go │ └── loops_test.go ├── mostcommon │ ├── mostcommon.go │ └── mostcommon_test.go ├── printfunction │ ├── main.go │ └── number │ │ ├── print.go │ │ └── print_test.go └── write-a-function │ ├── leap_year.go │ └── leap_year_test.go ├── clean-arch ├── README.md ├── cmd │ └── main.go ├── entity │ ├── user.go │ └── user_test.go ├── go.mod ├── go.sum └── usecase │ └── user │ ├── inmemory.go │ ├── interface.go │ └── service.go ├── dollar ├── README.md └── main.go ├── fizzbuzz ├── fizz.go └── fizz_test.go ├── goexample ├── .gitignore ├── Gopkg.lock ├── Gopkg.toml ├── Makefile ├── README.md ├── example │ └── main.go └── serverless.yml ├── gorotines ├── buffered-channels.go ├── calc-crazy.go ├── channels.go ├── concurrency.go ├── gorotines.go └── group.go ├── http-image └── main.go ├── http-server-template ├── index.html └── main.go ├── http-server ├── gin │ └── main.go └── main.go ├── methods-and-interfaces ├── interface.go ├── interfaces-are-satisfied-implicity.go └── methods.go ├── miscellany ├── add.go ├── clean_return.go ├── const.go ├── defer.go ├── fibonacci.go ├── file.go ├── mult_return.go ├── pi.go ├── pointer.go ├── rand.go ├── recursivo.go ├── short_variable.go ├── swap.go └── variable.go ├── mutex-group └── main.go ├── mutex └── main.go ├── pingpong ├── CHALLENGE.md ├── Makefile ├── go.mod ├── go.sum ├── ping.go └── ping_test.go ├── project_euler ├── problem_1 │ ├── README.md │ ├── mutiples.go │ └── mutiples_test.go └── problem_17 │ ├── README.md │ ├── number_letter_counts.go │ └── number_letter_counts_test.go ├── roman ├── numeral.go └── numeral_test.go ├── streaming ├── example_five │ └── main.go ├── example_four │ └── main.go ├── example_one │ └── main.go ├── example_three │ └── main.go └── example_two │ └── main.go ├── structs ├── append.go ├── closures.go ├── function_value.go ├── matrices.go ├── range.go ├── slices.go └── struct.go ├── wikipedia └── main.go ├── xml └── pizza │ └── main.go └── yml ├── example1 ├── example.yml └── main.go ├── example2 ├── example.yml └── main.go └── example3 ├── example.yml └── main.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | .DS_Store 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Estudos em Golang 2 | ================= 3 | 4 | Resolvi ampliar meus horizontes e ver a linguagem que eu mais gosto que é [Python](https://www.python.org) de outra perspectiva. 5 | Digo isso pois, sempre que eu estudo uma coisa nova eu acabo aprendendo mais sobre uma coisa que já sei, então 6 | resolvi aproveitar meu tempo livre e estudar [GoLang](https://golang.org), criei esse repositório para ajudar a outras pessoas 7 | que também estejam iniciando seus estudos, e não tenham material. Sinta-se a vontade para forkar e mandar seus pull requests, 8 | aprender junto é muito mais fácil. 9 | 10 | 11 | ### Links úteis: 12 | - https://tour.golang.org/welcome/1 13 | - https://go-tour-br.appspot.com/welcome/1 14 | - http://dojopuzzles.com 15 | - https://github.com/GoesToEleven/GolangTraining 16 | - https://github.com/avelino/awesome-go 17 | - https://gobyexample.com/ 18 | - https://www.goinggo.net/2013/10/manage-dependencies-with-godep.html 19 | - https://blog.codeship.com/building-minimal-docker-containers-for-go-applications/ 20 | - https://blog.learngoprogramming.com/golang-variadic-funcs-how-to-patterns-369408f19085 21 | - https://www.surenderthakran.com/articles/tech/dockerized-development-and-production-environment-golang 22 | - https://github.com/markcheno/api-golang-jwt 23 | - http://matthewbrown.io/2016/01/23/factory-pattern-in-golang/ 24 | - https://golangcode.com/convert-io-readcloser-to-a-string/ 25 | - http://blog.questionable.services/article/testing-http-handlers-go/ 26 | - https://medium.com/@kelvin_sp/building-and-testing-a-rest-api-in-golang-using-gorilla-mux-and-mysql-1f0518818ff6 27 | - https://blog.alexellis.io/golang-writing-unit-tests/ 28 | - https://golang.github.io/dep/ 29 | - https://ednsquare.com/publisher/view/Streaming-IO-in-Go-------T5aR56pC68 30 | - https://medium.com/build-acl/a-practical-guide-to-getting-started-with-aws-lambda-functions-using-go-3813abea730a 31 | - https://acervolima.com/mutex-em-golang-com-exemplos/ 32 | - https://gobyexample.com/mutexes 33 | - https://go.dev/tour/concurrency/9 34 | - https://eminetto.medium.com/clean-architecture-using-golang-b63587aa5e3f 35 | -------------------------------------------------------------------------------- /animals/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | // Animal -- 8 | type Animal struct { 9 | Name string 10 | mean bool 11 | } 12 | 13 | // AnimalSounder -- 14 | type AnimalSounder interface { 15 | MakeNoise() 16 | } 17 | 18 | // Dog -- 19 | type Dog struct { 20 | Animal 21 | BarkStrength int 22 | } 23 | 24 | // Cat -- 25 | type Cat struct { 26 | Basics Animal 27 | MeowStrength int 28 | } 29 | 30 | func main(){ 31 | myDog := &Dog{ 32 | Animal{ 33 | "Rover", 34 | false, 35 | }, 36 | 2, 37 | } 38 | 39 | myCat := &Cat{ 40 | Basics: Animal{ 41 | Name: "Julius", 42 | mean: true, 43 | }, 44 | MeowStrength: 3, 45 | } 46 | 47 | MakeSomeNoise(myDog) 48 | MakeSomeNoise(myCat) 49 | } 50 | 51 | // PerformNoise -- 52 | func (animal *Animal) PerformNoise(strength int, sound string){ 53 | if animal.mean == true { 54 | strength = strength * 5 55 | } 56 | 57 | for voice :=0; voice < strength; voice++ { 58 | fmt.Printf("%s ", sound) 59 | } 60 | 61 | fmt.Println() 62 | } 63 | 64 | // MakeNoise - 65 | func (dog *Dog) MakeNoise(){ 66 | dog.PerformNoise(dog.BarkStrength, "BARK") 67 | } 68 | 69 | // MakeNoise -- 70 | func (cat *Cat) MakeNoise(){ 71 | cat.Basics.PerformNoise(cat.MeowStrength, "MEOW") 72 | } 73 | // MakeSomeNoise -- 74 | func MakeSomeNoise(animalSounder AnimalSounder){ 75 | animalSounder.MakeNoise() 76 | } 77 | -------------------------------------------------------------------------------- /challenges/arithmetic/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "flag" 6 | ) 7 | 8 | // Arithmetic - 9 | type Arithmetic struct { 10 | x int 11 | y int 12 | } 13 | 14 | // ToCalc - 15 | func (a *Arithmetic) ToCalc () (int, int, int){ 16 | return a.Sum(), a.Difference(), a.Product() 17 | } 18 | 19 | // Sum - 20 | func (a *Arithmetic) Sum() int { 21 | return (a.x + a.y) 22 | } 23 | 24 | // Difference - 25 | func (a *Arithmetic) Difference() int { 26 | return (a.x - a.y) 27 | } 28 | 29 | // Product - 30 | func (a *Arithmetic) Product() int { 31 | return (a.x * a.y) 32 | } 33 | 34 | func main() { 35 | x := flag.Int("x", 0, "Should be a integer.") 36 | y := flag.Int("y", 0, "Should be a integer.") 37 | 38 | flag.Parse() 39 | 40 | ari := Arithmetic{*x, *y} 41 | log.Println(ari.ToCalc()) 42 | } 43 | -------------------------------------------------------------------------------- /challenges/arithmetic/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | "github.com/stretchr/testify/assert" 6 | ) 7 | 8 | func TestCalc_1(t *testing.T) { 9 | ari := Arithmetic{3, 2} 10 | a, b, c := ari.ToCalc() 11 | 12 | assert.Equal(t, a, 5) 13 | assert.Equal(t, b, 1) 14 | assert.Equal(t, c, 6) 15 | } 16 | 17 | func TestCalc_2(t *testing.T) { 18 | ari := Arithmetic{5, 2} 19 | a, b, c := ari.ToCalc() 20 | 21 | assert.Equal(t, a, 7) 22 | assert.Equal(t, b, 3) 23 | assert.Equal(t, c, 10) 24 | } 25 | -------------------------------------------------------------------------------- /challenges/capitalize/capitalize.go: -------------------------------------------------------------------------------- 1 | package capitalize 2 | 3 | import "strings" 4 | 5 | // Capitalize - 6 | func Capitalize(text string) string { 7 | data := strings.Split(text, " ") 8 | 9 | for pos, value := range data { 10 | data[pos] = strings.Title(value) 11 | } 12 | 13 | return strings.Join(data, " ") 14 | } 15 | -------------------------------------------------------------------------------- /challenges/capitalize/capitalize_test.go: -------------------------------------------------------------------------------- 1 | package capitalize 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestCap_1(t *testing.T) { 10 | cap := Capitalize("hello world") 11 | 12 | assert.Equal(t, cap, "Hello World") 13 | } 14 | 15 | func TestCap_2(t *testing.T) { 16 | cap := Capitalize("12abc") 17 | 18 | assert.Equal(t, cap, "12abc") 19 | } 20 | 21 | func TestCap_3(t *testing.T) { 22 | cap := Capitalize("1 2 3 4 5 6 8") 23 | 24 | assert.Equal(t, cap, "1 2 3 4 5 6 8") 25 | } 26 | 27 | func TestCap_4(t *testing.T) { 28 | cap := Capitalize("q w e r t y u i o p a s d f g h j k l z x c v b n m Q W E R T Y U I O P A S D F G H J K L Z X C V B N M") 29 | 30 | assert.Equal(t, cap, "Q W E R T Y U I O P A S D F G H J K L Z X C V B N M Q W E R T Y U I O P A S D F G H J K L Z X C V B N M") 31 | } 32 | -------------------------------------------------------------------------------- /challenges/find-a-string/find.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "log" 4 | 5 | // CountSubstring - 6 | func CountSubstring(s, sub string) int { 7 | occurrences := 0 8 | 9 | for i := range s { 10 | length := len(sub) + i 11 | 12 | cut := s[i:length] 13 | 14 | if cut == sub { 15 | occurrences++ 16 | } 17 | 18 | if length == len(s) { 19 | break 20 | } 21 | 22 | } 23 | 24 | return occurrences 25 | } 26 | 27 | func main() { 28 | log.Println(CountSubstring("ABCDCDC", "CDC")) 29 | 30 | } 31 | -------------------------------------------------------------------------------- /challenges/find-a-string/find_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func Test_should_get_2(t *testing.T) { 10 | response := CountSubstring("ABCDCDC", "CDC") 11 | assert.Equal(t, response, 2) 12 | } 13 | 14 | func Test_should_get_3(t *testing.T) { 15 | response := CountSubstring("ABCDCDCAAAACDC", "CDC") 16 | assert.Equal(t, response, 3) 17 | } 18 | -------------------------------------------------------------------------------- /challenges/loops/loops.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | // Calculate - 9 | func Calculate(number int) float64 { 10 | return math.Pow(float64(number), 2.0) 11 | } 12 | 13 | func main() { 14 | 15 | for n := 0; n < 5; n++ { 16 | if n >= 0 { 17 | fmt.Println(Calculate(n)) 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /challenges/loops/loops_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func Test_number_1(t *testing.T) { 10 | result := Calculate(1) 11 | 12 | assert.Equal(t, result, 1.0) 13 | } 14 | 15 | func Test_number_4(t *testing.T) { 16 | result := Calculate(4) 17 | 18 | assert.Equal(t, result, 16.0) 19 | } 20 | -------------------------------------------------------------------------------- /challenges/mostcommon/mostcommon.go: -------------------------------------------------------------------------------- 1 | package mostcommon 2 | 3 | import ( 4 | "errors" 5 | "sort" 6 | ) 7 | 8 | // Common - 9 | type Common struct { 10 | Key string 11 | Value int 12 | } 13 | 14 | // Most - 15 | type Most struct { 16 | Char string 17 | ListCommon []Common 18 | } 19 | 20 | // Shake - 21 | func (m *Most) Shake() { 22 | dict := make(map[string]int) 23 | 24 | for _, char := range m.Char { 25 | if _, ok := dict[string(char)]; ok { 26 | dict[string(char)]++ 27 | } else { 28 | dict[string(char)] = 1 29 | } 30 | } 31 | 32 | for key, value := range dict { 33 | m.ListCommon = append(m.ListCommon, Common{key, value}) 34 | } 35 | 36 | sort.Slice(m.ListCommon, func(i int, j int) bool { 37 | return m.ListCommon[i].Value > m.ListCommon[j].Value 38 | }) 39 | } 40 | 41 | // Chocolate - 42 | func (m *Most) Chocolate() (Common, error) { 43 | if len(m.ListCommon) == 0 { 44 | return Common{"@", -1}, errors.New("sorry the chocolate wasnt shaked") 45 | } 46 | return m.ListCommon[0], nil 47 | } 48 | 49 | // Strawberry - 50 | func (m *Most) Strawberry() (Common, error) { 51 | if len(m.ListCommon) == 1 { 52 | return Common{"@", -1}, errors.New("sorry the strawberry wasnt shaked") 53 | } 54 | return m.ListCommon[1], nil 55 | } 56 | 57 | // Vanilla - 58 | func (m *Most) Vanilla() (Common, error) { 59 | if len(m.ListCommon) < 2 { 60 | return Common{"@", -1}, errors.New("sorry the vanilla wasnt shaked") 61 | } 62 | return m.ListCommon[2], nil 63 | } 64 | -------------------------------------------------------------------------------- /challenges/mostcommon/mostcommon_test.go: -------------------------------------------------------------------------------- 1 | package mostcommon 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestGet322forBac(t *testing.T) { 10 | m := &Most{Char: "aabbbccde"} 11 | m.Shake() 12 | 13 | cholate, _ := m.Chocolate() 14 | strawberry, _ := m.Strawberry() 15 | vanilla, _ := m.Vanilla() 16 | 17 | assert.Equal(t, cholate, Common{"b", 3}) 18 | assert.Equal(t, strawberry, Common{"a", 2}) 19 | assert.Equal(t, vanilla, Common{"c", 2}) 20 | } 21 | 22 | func TestGet4forA(t *testing.T) { 23 | m := &Most{Char: "aaaa"} 24 | m.Shake() 25 | 26 | cholate, _ := m.Chocolate() 27 | _, strawberror := m.Strawberry() 28 | _, vanillerror := m.Vanilla() 29 | 30 | assert.Equal(t, cholate, Common{"a", 4}) 31 | assert.NotNil(t, strawberror) 32 | assert.NotNil(t, vanillerror) 33 | } 34 | -------------------------------------------------------------------------------- /challenges/printfunction/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | number "github.com/riquellopes/golang/challenges/printfunction/number" 7 | ) 8 | 9 | func main() { 10 | fmt.Println(number.Prints(5)) 11 | } 12 | -------------------------------------------------------------------------------- /challenges/printfunction/number/print.go: -------------------------------------------------------------------------------- 1 | package number 2 | 3 | import ( 4 | "strconv" 5 | "strings" 6 | ) 7 | 8 | // Prints - 9 | func Prints(number int) string { 10 | list := make([]string, number) 11 | 12 | for i := 0; i < number; i++ { 13 | list[i] = strconv.Itoa(i + 1) 14 | } 15 | return strings.Join(list, "") 16 | } 17 | -------------------------------------------------------------------------------- /challenges/printfunction/number/print_test.go: -------------------------------------------------------------------------------- 1 | package number 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestNumberthree(t *testing.T) { 10 | sequencie := Prints(3) 11 | 12 | assert.Equal(t, sequencie, "123") 13 | } 14 | 15 | func TestNumberfive(t *testing.T) { 16 | sequencie := Prints(5) 17 | 18 | assert.Equal(t, sequencie, "12345") 19 | } 20 | -------------------------------------------------------------------------------- /challenges/write-a-function/leap_year.go: -------------------------------------------------------------------------------- 1 | package leapyear 2 | 3 | // isLeap - 4 | func isLeap(year int) bool { 5 | divisibleByFour := year%4 == 0 6 | 7 | divisibleByHundred := year%100 != 0 8 | 9 | if divisibleByFour && divisibleByHundred || year%400 == 0 { 10 | return true 11 | } 12 | return false 13 | } 14 | -------------------------------------------------------------------------------- /challenges/write-a-function/leap_year_test.go: -------------------------------------------------------------------------------- 1 | package leapyear 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func Test_2000_is_true(t *testing.T) { 10 | assert.True(t, isLeap(2000)) 11 | } 12 | 13 | func Test_2400_is_true(t *testing.T) { 14 | assert.True(t, isLeap(2400)) 15 | } 16 | 17 | func Test_1800_is_true(t *testing.T) { 18 | assert.False(t, isLeap(1800)) 19 | } 20 | 21 | func Test_1900_is_true(t *testing.T) { 22 | assert.False(t, isLeap(1900)) 23 | } 24 | 25 | func Test_2100_is_true(t *testing.T) { 26 | assert.False(t, isLeap(2100)) 27 | } 28 | 29 | func Test_2200_is_true(t *testing.T) { 30 | assert.False(t, isLeap(2200)) 31 | } 32 | 33 | func Test_2300_is_true(t *testing.T) { 34 | assert.False(t, isLeap(2300)) 35 | } 36 | 37 | func Test_2500_is_true(t *testing.T) { 38 | assert.False(t, isLeap(2500)) 39 | } 40 | -------------------------------------------------------------------------------- /clean-arch/README.md: -------------------------------------------------------------------------------- 1 | Simple clean 2 | ============ 3 | 4 | Hi, there. -------------------------------------------------------------------------------- /clean-arch/cmd/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/riquellopes/golang/clean-arch/usecase/user" 7 | ) 8 | 9 | func main() { 10 | fmt.Println("Start cmd") 11 | 12 | repository := user.NewRepository() 13 | service := user.NewService(repository) 14 | 15 | // Create one 16 | service.CreateUser("Henrique", 40) 17 | 18 | users := service.ListUsers() 19 | 20 | for _, u := range users { 21 | fmt.Printf("%s %d \n", u.Name, u.Age) 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /clean-arch/entity/user.go: -------------------------------------------------------------------------------- 1 | package entity 2 | 3 | import "errors" 4 | 5 | type User struct { 6 | ID int 7 | Name string 8 | Age int 9 | } 10 | 11 | func NewUser(name string, age int) (*User, error) { 12 | user := &User{ 13 | ID: 0, 14 | Name: name, 15 | Age: age, 16 | } 17 | 18 | if err := user.Validate(); err != nil { 19 | return nil, err 20 | } 21 | 22 | return user, nil 23 | } 24 | 25 | func (u *User) Validate() error { 26 | if u.Name == "" || u.Age == 0 { 27 | return errors.New("Invalid params") 28 | } 29 | return nil 30 | } 31 | -------------------------------------------------------------------------------- /clean-arch/entity/user_test.go: -------------------------------------------------------------------------------- 1 | package entity 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestCreateUser(t *testing.T) { 10 | u, _ := NewUser("Henrique Lopes", 40) 11 | assert.Equal(t, u.Name, "Henrique Lopes") 12 | assert.Equal(t, u.Age, 40) 13 | } 14 | 15 | func TestCreateAnInvalidUser(t *testing.T) { 16 | _, err := NewUser("Henrique Lopes", 0) 17 | assert.NotNil(t, err) 18 | } 19 | -------------------------------------------------------------------------------- /clean-arch/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/riquellopes/golang/clean-arch 2 | 3 | go 1.19 4 | 5 | require github.com/stretchr/testify v1.8.1 6 | 7 | require ( 8 | github.com/davecgh/go-spew v1.1.1 // indirect 9 | github.com/pmezard/go-difflib v1.0.0 // indirect 10 | gopkg.in/yaml.v3 v3.0.1 // indirect 11 | ) 12 | -------------------------------------------------------------------------------- /clean-arch/go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 2 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 3 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 5 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 6 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 7 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 8 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 9 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 10 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 11 | github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= 12 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 13 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 14 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 15 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 16 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 17 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 18 | -------------------------------------------------------------------------------- /clean-arch/usecase/user/inmemory.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import "github.com/riquellopes/golang/clean-arch/entity" 4 | 5 | type inmemory struct { 6 | m map[int]*entity.User 7 | } 8 | 9 | func NewRepository() *inmemory { 10 | var memo = map[int]*entity.User{} 11 | return &inmemory{ 12 | m: memo, 13 | } 14 | } 15 | 16 | func (i *inmemory) List() []*entity.User { 17 | var d []*entity.User 18 | for _, j := range i.m { 19 | d = append(d, j) 20 | } 21 | return d 22 | } 23 | 24 | func (i *inmemory) Create(u *entity.User) error { 25 | i.m[0] = u 26 | return nil 27 | } 28 | -------------------------------------------------------------------------------- /clean-arch/usecase/user/interface.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "github.com/riquellopes/golang/clean-arch/entity" 5 | ) 6 | 7 | type Reader interface { 8 | List() []*entity.User 9 | } 10 | 11 | type Write interface { 12 | Create(e *entity.User) error 13 | } 14 | 15 | type Repository interface { 16 | Reader 17 | Write 18 | } 19 | 20 | type UserCase interface { 21 | ListUsers() []*entity.User 22 | } 23 | -------------------------------------------------------------------------------- /clean-arch/usecase/user/service.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import "github.com/riquellopes/golang/clean-arch/entity" 4 | 5 | type Service struct { 6 | repo Repository 7 | } 8 | 9 | func NewService(r Repository) *Service { 10 | return &Service{ 11 | repo: r, 12 | } 13 | } 14 | 15 | func (s *Service) ListUsers() []*entity.User { 16 | return s.repo.List() 17 | } 18 | 19 | func (s *Service) CreateUser(name string, age int) (*entity.User, error) { 20 | user, err := entity.NewUser(name, age) 21 | 22 | if err != nil { 23 | return nil, err 24 | } 25 | 26 | s.repo.Create(user) 27 | return user, nil 28 | } 29 | -------------------------------------------------------------------------------- /dollar/README.md: -------------------------------------------------------------------------------- 1 | Dollar 2 | ====== 3 | 4 | Create a simple Api that get dollar quote. For this challenge can you use the [Cotação API](https://economia.awesomeapi.com.br/last/USD-BRL). 5 | -------------------------------------------------------------------------------- /dollar/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "io/ioutil" 6 | "log" 7 | "net/http" 8 | ) 9 | 10 | type ResquestResultDollar struct { 11 | Usdbrl struct { 12 | Code string `json:"code"` 13 | Codein string `json:"codein"` 14 | Name string `json:"name"` 15 | High string `json:"high"` 16 | Low string `json:"low"` 17 | VarBid string `json:"varBid"` 18 | PctChange string `json:"pctChange"` 19 | Bid string `json:"bid"` 20 | Ask string `json:"ask"` 21 | Timestamp string `json:"timestamp"` 22 | CreateDate string `json:"create_date"` 23 | } `json:"USDBRL"` 24 | } 25 | 26 | // Parse - 27 | func Parse(response string) *ResquestResultDollar { 28 | result := new(ResquestResultDollar) 29 | err := json.Unmarshal([]byte(response), result) 30 | 31 | if err != nil { 32 | log.Println(err) 33 | } 34 | 35 | log.Println(result) 36 | return result 37 | } 38 | 39 | func request() (string, error) { 40 | log.Println("Iniciando request") 41 | response, err := http.Get( 42 | "https://economia.awesomeapi.com.br/last/USD-BRL") 43 | 44 | if err != nil { 45 | return "", err 46 | } 47 | 48 | log.Println("Recuperado request") 49 | 50 | // Close request 51 | defer func() { 52 | err := response.Body.Close() 53 | 54 | if err != nil { 55 | log.Println("Error to close request.") 56 | } 57 | }() 58 | 59 | contents, err := ioutil.ReadAll(response.Body) 60 | 61 | if err != nil { 62 | return "", err 63 | } 64 | 65 | return string(contents), nil 66 | } 67 | 68 | func main() { 69 | if response, err := request(); err == nil { 70 | parse := Parse(response) 71 | 72 | log.Println(parse.Usdbrl.Bid) 73 | } 74 | 75 | log.Println("Show") 76 | } 77 | -------------------------------------------------------------------------------- /fizzbuzz/fizz.go: -------------------------------------------------------------------------------- 1 | package fizzbuzz 2 | 3 | import "strconv" 4 | 5 | // Calculate - 6 | func Calculate(numeric, divisor int, text string) string { 7 | if numeric > 0 && numeric % divisor == 0 { 8 | return text 9 | } 10 | return "" 11 | } 12 | 13 | // FizzBuzz - Just improving my golang skill 14 | func FizzBuzz(numeric int) string { 15 | FizzBuzz := Calculate(numeric, 3, "fizz") + Calculate(numeric, 5, "buzz") 16 | 17 | if len(FizzBuzz) > 0 { 18 | return FizzBuzz 19 | } 20 | 21 | return strconv.Itoa(numeric) 22 | } 23 | -------------------------------------------------------------------------------- /fizzbuzz/fizz_test.go: -------------------------------------------------------------------------------- 1 | package fizzbuzz 2 | 3 | import ( 4 | "testing" 5 | "github.com/stretchr/testify/assert" 6 | ) 7 | 8 | func TestFizzBuzz_0(t *testing.T) { 9 | fizzbuzz := FizzBuzz(0) 10 | assert.Equal(t, fizzbuzz, "0") 11 | } 12 | 13 | func TestFizzBuzz_1(t *testing.T) { 14 | fizzbuzz := FizzBuzz(1) 15 | assert.Equal(t, fizzbuzz, "1") 16 | } 17 | 18 | func TestFizzBuzz_3(t *testing.T) { 19 | fizzbuzz := FizzBuzz(3) 20 | assert.Equal(t, fizzbuzz, "fizz") 21 | } 22 | 23 | func TestFizzBuzz_9(t *testing.T) { 24 | fizzbuzz := FizzBuzz(9) 25 | assert.Equal(t, fizzbuzz, "fizz") 26 | } 27 | 28 | func TestFizzBuzz_5(t *testing.T) { 29 | fizzbuzz := FizzBuzz(5) 30 | assert.Equal(t, fizzbuzz, "buzz") 31 | } 32 | 33 | func TestFizzBuzz_25(t *testing.T) { 34 | fizzbuzz := FizzBuzz(25) 35 | assert.Equal(t, fizzbuzz, "buzz") 36 | } 37 | 38 | func TestFizzBuzz_15(t *testing.T) { 39 | fizzbuzz := FizzBuzz(15) 40 | assert.Equal(t, fizzbuzz, "fizzbuzz") 41 | } 42 | -------------------------------------------------------------------------------- /goexample/.gitignore: -------------------------------------------------------------------------------- 1 | # Serverless directories 2 | .serverless 3 | 4 | # golang output binary directory 5 | bin 6 | 7 | # golang vendor (dependencies) directory 8 | vendor -------------------------------------------------------------------------------- /goexample/Gopkg.lock: -------------------------------------------------------------------------------- 1 | # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. 2 | 3 | 4 | [[projects]] 5 | name = "github.com/aws/aws-lambda-go" 6 | packages = [ 7 | "lambda", 8 | "lambda/messages", 9 | "lambdacontext" 10 | ] 11 | revision = "4d30d0ff60440c2d0480a15747c96ee71c3c53d4" 12 | version = "v1.2.0" 13 | 14 | [solve-meta] 15 | analyzer-name = "dep" 16 | analyzer-version = 1 17 | inputs-digest = "aade89244f734c9363d131e4c1d41bd8c1519060c8519c09763168caf6e193f3" 18 | solver-name = "gps-cdcl" 19 | solver-version = 1 20 | -------------------------------------------------------------------------------- /goexample/Gopkg.toml: -------------------------------------------------------------------------------- 1 | # Gopkg.toml example 2 | # 3 | # Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md 4 | # for detailed Gopkg.toml documentation. 5 | # 6 | # required = ["github.com/user/thing/cmd/thing"] 7 | # ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] 8 | # 9 | # [[constraint]] 10 | # name = "github.com/user/project" 11 | # version = "1.0.0" 12 | # 13 | # [[constraint]] 14 | # name = "github.com/user/project2" 15 | # branch = "dev" 16 | # source = "github.com/myfork/project2" 17 | # 18 | # [[override]] 19 | # name = "github.com/x/y" 20 | # version = "2.4.0" 21 | 22 | 23 | [[constraint]] 24 | name = "github.com/aws/aws-lambda-go" 25 | version = "1.x" 26 | -------------------------------------------------------------------------------- /goexample/Makefile: -------------------------------------------------------------------------------- 1 | build: 2 | dep ensure 3 | env GOOS=linux go build -ldflags="-s -w" -o bin/example example/main.go 4 | -------------------------------------------------------------------------------- /goexample/README.md: -------------------------------------------------------------------------------- 1 | Go example 2 | ========== 3 | 4 | This's code is a simple example of [serverless](https://serverless.com/blog/framework-example-golang-lambda-support/) use with Golang. 5 | -------------------------------------------------------------------------------- /goexample/example/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/aws/aws-lambda-go/lambda" 5 | ) 6 | 7 | type Response struct { 8 | Message string `json:"message"` 9 | } 10 | 11 | func Handler() (Response, error) { 12 | return Response{ 13 | Message: "Go Serverless v1.0! Your function executed successfully!", 14 | }, nil 15 | } 16 | 17 | func main() { 18 | lambda.Start(Handler) 19 | } 20 | -------------------------------------------------------------------------------- /goexample/serverless.yml: -------------------------------------------------------------------------------- 1 | # Welcome to Serverless! 2 | # 3 | # This file is the main config file for your service. 4 | # It's very minimal at this point and uses default values. 5 | # You can always add more config options for more control. 6 | # We've included some commented out config examples here. 7 | # Just uncomment any of them to get that config option. 8 | # 9 | # For full config options, check the docs: 10 | # docs.serverless.com 11 | # 12 | # Happy Coding! 13 | 14 | service: goexample 15 | 16 | # You can pin your service to only deploy with a specific Serverless version 17 | # Check out our docs for more details 18 | # frameworkVersion: "=X.X.X" 19 | 20 | provider: 21 | name: aws 22 | profile: serverless-admin 23 | region: us-east-1 24 | runtime: go1.x 25 | 26 | package: 27 | exclude: 28 | - ./** 29 | include: 30 | - ./bin/** 31 | 32 | functions: 33 | example: 34 | handler: bin/example 35 | -------------------------------------------------------------------------------- /gorotines/buffered-channels.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main(){ 6 | c := make(chan int, 2) 7 | c <- 1 8 | c <- 2 9 | 10 | fmt.Println(<-c) 11 | fmt.Println(<-c) 12 | } 13 | -------------------------------------------------------------------------------- /gorotines/calc-crazy.go: -------------------------------------------------------------------------------- 1 | package calccrazy 2 | 3 | import "fmt" 4 | 5 | func Calc(c chan float64) { 6 | c <- 2.3423 / 534.23423 7 | 8 | } 9 | 10 | func UserGoRoutine() float64 { 11 | canal := make(chan float64) 12 | 13 | go Calc(canal) 14 | 15 | return <-canal 16 | } 17 | 18 | func main() { 19 | valor := UserGoRoutine() 20 | fmt.Printf("The result was: %v \n", valor) 21 | } 22 | -------------------------------------------------------------------------------- /gorotines/channels.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func sum(a []int, c chan int){ 6 | sum := 0 7 | for _, v := range a { 8 | sum += v 9 | } 10 | 11 | c <- sum 12 | } 13 | 14 | func main(){ 15 | a := []int{7, 2, 8, -9, 4, 0} 16 | 17 | c := make(chan int) 18 | go sum(a[:len(a)/2], c) 19 | go sum(a[len(a)/2:], c) 20 | 21 | x, y := <-c, <-c 22 | 23 | fmt.Println(x, y, x+y) 24 | } 25 | -------------------------------------------------------------------------------- /gorotines/concurrency.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | go foo() 7 | go bar() 8 | } 9 | 10 | func foo() { 11 | for i := 0; i<45; i++ { 12 | fmt.Println("Foo:", i) 13 | } 14 | } 15 | 16 | func bar() { 17 | for i := 0; i<45; i++ { 18 | fmt.Println("Bar:", i) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /gorotines/gorotines.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func say(s string){ 9 | for i:=0; i<5; i++{ 10 | time.Sleep(100*time.Millisecond) 11 | fmt.Println(s) 12 | } 13 | } 14 | 15 | func main(){ 16 | go say("World") 17 | say("Hello") 18 | } 19 | -------------------------------------------------------------------------------- /gorotines/group.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | ) 7 | 8 | var wg sync.WaitGroup 9 | 10 | func main() { 11 | wg.Add(2) 12 | go foo() 13 | go bar() 14 | wg.Wait() 15 | } 16 | 17 | func foo() { 18 | for i := 0; i<45; i++ { 19 | fmt.Println("Foo:", i) 20 | } 21 | 22 | wg.Done() 23 | } 24 | 25 | func bar() { 26 | for i := 0; i<45; i++ { 27 | fmt.Println("Bar:", i) 28 | } 29 | 30 | wg.Done() 31 | } 32 | -------------------------------------------------------------------------------- /http-image/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "net/http" 6 | "image" 7 | "log" 8 | "image/color" 9 | "image/draw" 10 | "image/jpeg" 11 | "strconv" 12 | ) 13 | 14 | 15 | func imageHandler(request http.ResponseWriter, response *http.Request){ 16 | rgb := image.NewRGBA(image.Rect(0, 0, 1, 1)) 17 | black := color.RGBA{0, 0, 0, 255} 18 | draw.Draw(rgb, rgb.Bounds(), &image.Uniform{black}, image.ZP, draw.Src) 19 | 20 | var img image.Image = rgb 21 | 22 | buffer := new(bytes.Buffer) 23 | if err := jpeg.Encode(buffer, img, nil); err != nil { 24 | log.Println("unable to encode image.") 25 | } 26 | 27 | request.Header().Set("Content-Type", "image/jpeg") 28 | request.Header().Set("Content-Length", strconv.Itoa(len(buffer.Bytes()))) 29 | if _, err := request.Write(buffer.Bytes()); err != nil { 30 | log.Println("unable to write image.") 31 | } 32 | 33 | log.Println(response.Header) 34 | } 35 | 36 | 37 | func main(){ 38 | http.HandleFunc("/image.jpg", imageHandler) 39 | 40 | log.Println("Listening :5000") 41 | err := http.ListenAndServe(":5000", nil) 42 | 43 | if err != nil { 44 | log.Fatal("Erro server", err) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /http-server-template/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Hello | GoLang 4 | 5 | 6 |

Hello Golang

7 | 8 | 9 | -------------------------------------------------------------------------------- /http-server-template/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "html/template" 5 | "io" 6 | "log" 7 | "net/http" 8 | ) 9 | 10 | func home(res http.ResponseWriter, req *http.Request){ 11 | io.WriteString(res, "Home") 12 | } 13 | 14 | func hello(res http.ResponseWriter, req *http.Request){ 15 | tpl, err := template.ParseFiles("index.html") 16 | if err != nil { 17 | log.Fatalln(err) 18 | } 19 | 20 | tpl.Execute(res, nil) 21 | } 22 | 23 | func main(){ 24 | http.HandleFunc("/", home) 25 | http.HandleFunc("/hello.html", hello) 26 | http.ListenAndServe(":5000", nil) 27 | } 28 | -------------------------------------------------------------------------------- /http-server/gin/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "github.com/gin-gonic/gin" 4 | 5 | 6 | func main(){ 7 | r := gin.Default() 8 | 9 | r.GET("/ping", func(c *gin.Context){ 10 | c.JSON(200, gin.H{ 11 | "message": "pong", 12 | }) 13 | }) 14 | 15 | r.Run() 16 | } 17 | -------------------------------------------------------------------------------- /http-server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io" 5 | "net/http" 6 | ) 7 | 8 | func foo(res http.ResponseWriter, req *http.Request){ 9 | io.WriteString(res, "foo ran") 10 | } 11 | 12 | func bar(res http.ResponseWriter, req *http.Request){ 13 | io.WriteString(res, "bar ran") 14 | } 15 | 16 | func main(){ 17 | http.HandleFunc("/", foo) 18 | http.HandleFunc("/dog/", bar) 19 | http.ListenAndServe(":8080", nil) 20 | } 21 | -------------------------------------------------------------------------------- /methods-and-interfaces/interface.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | type Abser interface { 9 | Abs() float64 10 | } 11 | 12 | func main(){ 13 | var a Abser 14 | f := MyFloat(-math.Sqrt2) 15 | v := Vertex{3, 4} 16 | 17 | a = f 18 | a = &v 19 | 20 | fmt.Println(a.Abs()) 21 | } 22 | 23 | type MyFloat float64 24 | 25 | func (f MyFloat) Abs() float64 { 26 | if f < 0 { 27 | return float64(-f) 28 | } 29 | 30 | return float64(f) 31 | } 32 | 33 | type Vertex struct { 34 | X, Y float64 35 | } 36 | 37 | func (v *Vertex) Abs() float64 { 38 | return math.Sqrt(v.X*v.X + v.Y*v.Y) 39 | } 40 | -------------------------------------------------------------------------------- /methods-and-interfaces/interfaces-are-satisfied-implicity.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | ) 7 | 8 | type Reader interface { 9 | Read(b []byte) (n int, err error) 10 | } 11 | 12 | type Writer interface { 13 | Write(b []byte) (n int, err error) 14 | } 15 | 16 | type ReadWriter interface { 17 | Reader 18 | Writer 19 | } 20 | 21 | func main(){ 22 | var w Writer 23 | 24 | w = os.Stdout 25 | 26 | fmt.Fprintf(w, "Hello, writer\n") 27 | } 28 | -------------------------------------------------------------------------------- /methods-and-interfaces/methods.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | 4 | import ( 5 | "fmt" 6 | "math" 7 | ) 8 | 9 | // Vertex - 10 | type Vertex struct { 11 | X, Y float64 12 | } 13 | 14 | // Abs - 15 | func (v *Vertex) Abs() float64{ 16 | return math.Sqrt(v.X*v.X + v.Y*v.Y) 17 | } 18 | 19 | func main(){ 20 | v := &Vertex{3, 4} 21 | fmt.Println(v.Abs()) 22 | } 23 | -------------------------------------------------------------------------------- /miscellany/add.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | 6 | func add(x, y int) int { 7 | return x+y 8 | } 9 | 10 | func main(){ 11 | fmt.Println(add(42, 13)) 12 | } 13 | -------------------------------------------------------------------------------- /miscellany/clean_return.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func split(sum int) (x, y int){ 6 | x = sum * 4 / 9 7 | y = sum - x 8 | return 9 | } 10 | 11 | func main(){ 12 | fmt.Println(split(17)) 13 | } 14 | -------------------------------------------------------------------------------- /miscellany/const.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | const Pi = 3.14 6 | 7 | func main(){ 8 | const World = "Mundo" 9 | 10 | fmt.Println("Olá", World) 11 | fmt.Println("Feliz", Pi, "Day") 12 | 13 | const Truth = true 14 | fmt.Println("Go Rules?", Truth) 15 | } 16 | -------------------------------------------------------------------------------- /miscellany/defer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main(){ 6 | defer fmt.Println("World") 7 | 8 | fmt.Println("Hello") 9 | } 10 | -------------------------------------------------------------------------------- /miscellany/fibonacci.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func fibonacci() func() int { 6 | x := 0 7 | y := 1 8 | return func() int{ 9 | x,y = y,x+y 10 | return x 11 | } 12 | } 13 | 14 | func main(){ 15 | f := fibonacci() 16 | for i:= 0; i<10; i++{ 17 | fmt.Println(f()) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /miscellany/file.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "io/ioutil" 4 | 5 | func main(){ 6 | texto := []byte("Conteudo") 7 | err := ioutil.WriteFile("/tmp/content.txt", texto, 0644) 8 | 9 | if err != nil { 10 | panic(err) 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /miscellany/mult_return.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func MultReturn() (name string, age int) { 6 | name = "Henrique Lopes" 7 | age = 35 8 | 9 | return 10 | } 11 | 12 | func main() { 13 | name, age := MultReturn() 14 | 15 | fmt.Println(name, age) 16 | } 17 | -------------------------------------------------------------------------------- /miscellany/pi.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | func main(){ 9 | fmt.Println(math.Pi) 10 | } 11 | -------------------------------------------------------------------------------- /miscellany/pointer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main(){ 6 | i, j := 42, 2701 7 | 8 | p := &i 9 | fmt.Println(*p) 10 | 11 | *p = 21 12 | fmt.Println(i) 13 | 14 | p = &j 15 | *p = *p / 37 16 | fmt.Println(j) 17 | } 18 | -------------------------------------------------------------------------------- /miscellany/rand.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | ) 7 | 8 | func main(){ 9 | fmt.Println("My favorite number is", rand.Intn(10)) 10 | } 11 | -------------------------------------------------------------------------------- /miscellany/recursivo.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func fact(n int) int { 6 | if n == 0 { 7 | return 1 8 | } 9 | 10 | return n * fact(n - 1) 11 | } 12 | 13 | func main(){ 14 | fmt.Println(fact(7)) 15 | } 16 | -------------------------------------------------------------------------------- /miscellany/short_variable.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main(){ 6 | var i, j int = 1, 2 7 | k := 3 8 | c, python, java := true, false, "no!" 9 | 10 | fmt.Println(i, j, k, c, python, java) 11 | } 12 | -------------------------------------------------------------------------------- /miscellany/swap.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func swap(x, y string) (string, string){ 6 | return x, y 7 | } 8 | 9 | 10 | func main(){ 11 | a, b := swap("Hello", "World") 12 | fmt.Println(a, b) 13 | } 14 | -------------------------------------------------------------------------------- /miscellany/variable.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | var c, python, java bool 6 | 7 | 8 | func main(){ 9 | var i int 10 | fmt.Println(i, c, python, java) 11 | } 12 | -------------------------------------------------------------------------------- /mutex-group/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | ) 7 | 8 | // https://acervolima.com/mutex-em-golang-com-exemplos/ 9 | 10 | var GFG = 0 11 | 12 | func worker(wg *sync.WaitGroup, m *sync.Mutex) { 13 | m.Lock() 14 | 15 | GFG = GFG + 1 16 | m.Unlock() 17 | 18 | wg.Done() 19 | } 20 | 21 | func main() { 22 | var w sync.WaitGroup 23 | 24 | var m sync.Mutex 25 | 26 | for i := 0; i < 1000; i++ { 27 | w.Add(1) 28 | 29 | go worker(&w, &m) 30 | } 31 | 32 | w.Wait() 33 | 34 | fmt.Println("Value of x", GFG) 35 | } 36 | -------------------------------------------------------------------------------- /mutex/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | "time" 7 | ) 8 | 9 | // https://go.dev/tour/concurrency/9 10 | type SafeCounter struct { 11 | mu sync.Mutex 12 | v map[string]int 13 | } 14 | 15 | func (c *SafeCounter) Inc(key string) { 16 | c.mu.Lock() 17 | 18 | c.v[key]++ 19 | c.mu.Unlock() 20 | } 21 | 22 | func (c *SafeCounter) Value(key string) int { 23 | c.mu.Lock() 24 | 25 | defer c.mu.Unlock() 26 | 27 | return c.v[key] 28 | } 29 | 30 | func main() { 31 | c := SafeCounter{v: make(map[string]int)} 32 | 33 | for i := 0; i < 1000; i++ { 34 | go c.Inc("somekey") 35 | } 36 | 37 | time.Sleep(time.Second) 38 | 39 | fmt.Println(c.Value("somekey")) 40 | } 41 | -------------------------------------------------------------------------------- /pingpong/CHALLENGE.md: -------------------------------------------------------------------------------- 1 | PingPong 2 | ======== 3 | Esse desafio é bem simples, consiste em toda a vez que um número for divisível por 3 a palavra 4 | **Ping** deve ser recuperada, quando o número for divisível por 5 a palavra **Pong**, quando 5 | for divisível por 3 e 5 deve recuperada apalavra **PingPong**. E quando não for divisível por nenhum 6 | desses números? Deve ser recuperada o próprio número. 7 | -------------------------------------------------------------------------------- /pingpong/Makefile: -------------------------------------------------------------------------------- 1 | test: 2 | go test -v ./... -------------------------------------------------------------------------------- /pingpong/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/riquellopes/golang/pingpong 2 | 3 | go 1.16 4 | 5 | require github.com/stretchr/testify v1.7.0 // indirect 6 | -------------------------------------------------------------------------------- /pingpong/go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 4 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 5 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 6 | github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= 7 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 8 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 9 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= 10 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 11 | -------------------------------------------------------------------------------- /pingpong/ping.go: -------------------------------------------------------------------------------- 1 | package pingpong 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | ) 7 | 8 | func ping(number int) string { 9 | var ( 10 | ping = "" 11 | pong = "" 12 | num = "" 13 | ) 14 | if divisible(number, 3) { 15 | ping = "Ping" 16 | } 17 | if divisible(number, 5) { 18 | pong = "Pong" 19 | } 20 | if len(ping) == 0 && len(pong) == 0 { 21 | num = strconv.Itoa(number) 22 | } 23 | return fmt.Sprintf("%s%s%s", ping, pong, num) 24 | } 25 | 26 | func divisible(number, divider int) bool { 27 | if (number % divider) == 0 { 28 | return true 29 | } 30 | return false 31 | } 32 | -------------------------------------------------------------------------------- /pingpong/ping_test.go: -------------------------------------------------------------------------------- 1 | package pingpong 2 | 3 | import ( 4 | "testing" 5 | "github.com/stretchr/testify/assert" 6 | ) 7 | 8 | 9 | func TestPingPong_para_o_numero_3_o_retorno_deve_ser_ping(t *testing.T){ 10 | pingPingo := ping(3) 11 | assert.Equal(t, pingPingo, "Ping") 12 | } 13 | 14 | func TestPingPong_para_o_numero_6_o_retorno_deve_ser_ping(t *testing.T){ 15 | pingPingo := ping(6) 16 | assert.Equal(t, pingPingo, "Ping") 17 | } 18 | 19 | func TestPingPong_para_o_numero_5_o_retorno_deve_ser_pong(t *testing.T){ 20 | pingPingo := ping(5) 21 | assert.Equal(t, pingPingo, "Pong") 22 | } 23 | 24 | func TestPingPong_para_o_numero_25_o_retorno_deve_ser_pong(t *testing.T){ 25 | pingPingo := ping(25) 26 | assert.Equal(t, pingPingo, "Pong") 27 | } 28 | 29 | func TestPingPong_para_o_numero_15_o_retorno_deve_ser_pingpong(t *testing.T){ 30 | pingPingo := ping(15) 31 | assert.Equal(t, pingPingo, "PingPong") 32 | } 33 | 34 | func TestPingPong_para_o_numero_45_o_retorno_deve_ser_pingpong(t *testing.T){ 35 | pingPingo := ping(45) 36 | assert.Equal(t, pingPingo, "PingPong") 37 | } 38 | 39 | func TestPingPong_para_o_numero_7_o_retorno_deve_ser_7(t *testing.T){ 40 | pingPingo := ping(7) 41 | assert.Equal(t, pingPingo, "7") 42 | } 43 | -------------------------------------------------------------------------------- /project_euler/problem_1/README.md: -------------------------------------------------------------------------------- 1 | [Link to the Euler's problems](https://projecteuler.net/index.php?section=problems&id=1) 2 | -------------------------------------------------------------------------------- /project_euler/problem_1/mutiples.go: -------------------------------------------------------------------------------- 1 | package problemOne 2 | 3 | // Multiple - 4 | func Multiple(below int) int { 5 | theSum := 0 6 | 7 | for i := 1; i < below; i++ { 8 | if i%3 == 0 || i%5 == 0 { 9 | theSum += i 10 | } 11 | } 12 | 13 | return theSum 14 | } 15 | -------------------------------------------------------------------------------- /project_euler/problem_1/mutiples_test.go: -------------------------------------------------------------------------------- 1 | package problemOne 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestShouldGet23(t *testing.T) { 10 | assert.Equal(t, Multiple(10), 23) 11 | } 12 | 13 | func TestShouldGet14(t *testing.T) { 14 | assert.Equal(t, Multiple(9), 14) 15 | } 16 | 17 | func TestShouldGet233168(t *testing.T) { 18 | assert.Equal(t, Multiple(1000), 233168) 19 | } 20 | -------------------------------------------------------------------------------- /project_euler/problem_17/README.md: -------------------------------------------------------------------------------- 1 | [Link to the Euler's problems](https://projecteuler.net/index.php?section=problems&id=17) 2 | 3 | #### OBS: 4 | I didn't use the British pattern to write the numbers, as was written in the resolution. 5 | -------------------------------------------------------------------------------- /project_euler/problem_17/number_letter_counts.go: -------------------------------------------------------------------------------- 1 | package problem17 2 | 3 | import ( 4 | "log" 5 | "regexp" 6 | 7 | "github.com/divan/num2words" 8 | ) 9 | 10 | // LettersUsed - 11 | type LettersUsed struct { 12 | S int 13 | E int 14 | } 15 | 16 | // Total - 17 | func (l *LettersUsed) Total() int { 18 | numberStr := "" 19 | 20 | for i := l.S; i <= l.E; i++ { 21 | numberStr += l.IntToWords(i) 22 | } 23 | 24 | return len(numberStr) 25 | } 26 | 27 | // IntToWords - 28 | func (l *LettersUsed) IntToWords(number int) string { 29 | words := num2words.Convert(number) 30 | reg, err := regexp.Compile("[^a-zA-Z]+") 31 | 32 | if err != nil { 33 | log.Fatal(err) 34 | } 35 | 36 | return reg.ReplaceAllString(words, "") 37 | } 38 | -------------------------------------------------------------------------------- /project_euler/problem_17/number_letter_counts_test.go: -------------------------------------------------------------------------------- 1 | package problem17 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestOneToFive(t *testing.T) { 10 | lettersUsed := LettersUsed{1, 5} 11 | 12 | assert.Equal(t, lettersUsed.Total(), 19) 13 | } 14 | 15 | func TestOneToTwo(t *testing.T) { 16 | lettersUsed := LettersUsed{1, 2} 17 | 18 | assert.Equal(t, lettersUsed.Total(), 6) 19 | } 20 | 21 | func TestShouldGetOnlyWords(t *testing.T) { 22 | lettersUsed := LettersUsed{1, 2} 23 | 24 | assert.Equal(t, lettersUsed.IntToWords(342), "threehundredfortytwo") 25 | } 26 | 27 | func TestOneToOneThousand(t *testing.T) { 28 | lettersUsed := LettersUsed{1, 1000} 29 | 30 | assert.Equal(t, lettersUsed.Total(), 18451) 31 | } 32 | -------------------------------------------------------------------------------- /roman/numeral.go: -------------------------------------------------------------------------------- 1 | package roman 2 | 3 | import "strings" 4 | 5 | func ArabicToRoman(n int) string { 6 | 7 | // romanNumerals := map[int] string { 8 | // 1: "I", 9 | // 5: "V", 10 | // 10: "X", 11 | // 50: "L", 12 | // 100: "C", 13 | // 500: "D", 14 | // 1000: "M", 15 | // } 16 | 17 | if n == 5 { 18 | return "V" 19 | } else if n == 4 { 20 | return "IV" 21 | } 22 | return strings.Repeat("I", n) 23 | } 24 | -------------------------------------------------------------------------------- /roman/numeral_test.go: -------------------------------------------------------------------------------- 1 | package roman 2 | 3 | import ( 4 | "testing" 5 | "github.com/stretchr/testify/assert" 6 | ) 7 | 8 | func TestArabic_1_should_roman_I(t *testing.T) { 9 | 10 | arabicToRoman := ArabicToRoman(1) 11 | assert.Equal(t, arabicToRoman, "I") 12 | } 13 | 14 | func TestArabic_2_should_roman_II(t *testing.T) { 15 | 16 | arabicToRoman := ArabicToRoman(2) 17 | assert.Equal(t, arabicToRoman, "II") 18 | } 19 | -------------------------------------------------------------------------------- /streaming/example_five/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "os" 7 | ) 8 | 9 | func main() { 10 | proverbs := []string{ 11 | "Jesus is love", 12 | "For God so loved the world that", 13 | } 14 | 15 | var writer bytes.Buffer 16 | 17 | for _, p := range proverbs { 18 | n, err := writer.Write([]byte(p)) 19 | 20 | if err != nil { 21 | fmt.Println(err) 22 | os.Exit(1) 23 | } 24 | 25 | if n != len(p) { 26 | fmt.Println("Failed to write data") 27 | os.Exit(1) 28 | } 29 | } 30 | 31 | fmt.Println(writer.String()) 32 | } 33 | -------------------------------------------------------------------------------- /streaming/example_four/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "os" 7 | ) 8 | 9 | type alphaReader struct { 10 | reader io.Reader 11 | } 12 | 13 | func newAlphaReader(reader io.Reader) *alphaReader { 14 | return &alphaReader{reader: reader} 15 | } 16 | 17 | func alpha(r byte) byte { 18 | if (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') { 19 | return r 20 | } 21 | return 0 22 | } 23 | 24 | func (a *alphaReader) Read(p []byte) (int, error) { 25 | n, err := a.reader.Read(p) 26 | if err != nil { 27 | return n, err 28 | } 29 | buf := make([]byte, n) 30 | for i := 0; i < n; i++ { 31 | if char := alpha(p[i]); char != 0 { 32 | buf[i] = char 33 | } 34 | } 35 | 36 | copy(p, buf) 37 | return n, nil 38 | } 39 | 40 | // Bug 41 | func main() { 42 | file, err := os.Open("./../example_one/main.go") 43 | 44 | if err != nil { 45 | fmt.Println(err) 46 | os.Exit(1) 47 | } 48 | 49 | defer file.Close() 50 | 51 | reader := newAlphaReader(file) 52 | p := make([]byte, 4) 53 | 54 | for { 55 | n, err := reader.Read(p) 56 | if err != io.EOF { 57 | break 58 | } 59 | 60 | fmt.Print(string(p[:n])) 61 | } 62 | 63 | fmt.Println() 64 | } 65 | -------------------------------------------------------------------------------- /streaming/example_one/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "strings" 7 | ) 8 | 9 | func main() { 10 | reader := strings.NewReader("First example with streaming") 11 | p := make([]byte, 4) 12 | 13 | for { 14 | n, err := reader.Read(p) 15 | 16 | if err == io.EOF { 17 | break 18 | } 19 | 20 | fmt.Print(string(p[:n])) 21 | } 22 | 23 | fmt.Println("") 24 | } 25 | -------------------------------------------------------------------------------- /streaming/example_three/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | ) 7 | 8 | type AlphaReader struct { 9 | src string 10 | cur int 11 | } 12 | 13 | func newAlphaReader(src string) *AlphaReader { 14 | return &AlphaReader{src: src} 15 | } 16 | 17 | func alpha(r byte) byte { 18 | if (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') { 19 | return r 20 | } 21 | 22 | return 0 23 | } 24 | 25 | func (a *AlphaReader) Read(p []byte) (int, error) { 26 | if a.cur >= len(a.src) { 27 | return 0, io.EOF 28 | } 29 | 30 | x := len(a.src) - a.cur 31 | n, bound := 0, 0 32 | 33 | if x >= len(p) { 34 | bound = len(p) 35 | } else if x <= len(p) { 36 | bound = x 37 | } 38 | 39 | buf := make([]byte, bound) 40 | for n < bound { 41 | if char := alpha(a.src[a.cur]); char != 0 { 42 | buf[n] = char 43 | } 44 | 45 | n++ 46 | a.cur++ 47 | } 48 | 49 | copy(p, buf) 50 | return n, nil 51 | } 52 | 53 | func main() { 54 | reader := newAlphaReader("Hello guys, this is my 3th streaming example.") 55 | p := make([]byte, 4) 56 | 57 | for { 58 | n, err := reader.Read(p) 59 | 60 | if err == io.EOF { 61 | break 62 | } 63 | 64 | fmt.Print(string(p[:n])) 65 | } 66 | 67 | fmt.Println() 68 | } 69 | -------------------------------------------------------------------------------- /streaming/example_two/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "os" 7 | "strings" 8 | ) 9 | 10 | func main() { 11 | reader := strings.NewReader("My second example with streaming.") 12 | p := make([]byte, 4) 13 | 14 | for { 15 | n, err := reader.Read(p) 16 | if err != nil { 17 | if err != io.EOF { 18 | fmt.Println(string(p[:n])) 19 | break 20 | } 21 | 22 | fmt.Println(err) 23 | os.Exit(1) 24 | } 25 | 26 | fmt.Println(string(p[:n])) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /structs/append.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main(){ 6 | var a []int 7 | printSlice("a", a) 8 | 9 | a = append(a, 0) 10 | printSlice("a", a) 11 | 12 | a = append(a, 1) 13 | printSlice("a", a) 14 | 15 | a = append(a, 2, 3, 4, 5) 16 | printSlice("a", a) 17 | } 18 | 19 | func printSlice(s string, x []int){ 20 | fmt.Printf("%s len=%d cap=%d %v\n", s, len(x), cap(x), x) 21 | } 22 | -------------------------------------------------------------------------------- /structs/closures.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func adder() func(int) int { 6 | sum := 0 7 | return func(x int) int { 8 | sum +=x 9 | return sum 10 | } 11 | } 12 | 13 | func main(){ 14 | pos, neg := adder(), adder() 15 | 16 | for i :=0; i<10; i++{ 17 | fmt.Println( 18 | pos(i), 19 | neg(-2*i), 20 | ) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /structs/function_value.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | //feeling happy! 9 | func main(){ 10 | hypot := func(x, y float64) float64{ 11 | return math.Sqrt(x*x + y*y) 12 | } 13 | 14 | fmt.Println(hypot(3, 4)) 15 | } 16 | -------------------------------------------------------------------------------- /structs/matrices.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main(){ 6 | var a [2]string 7 | a[0] = "Hello" 8 | a[1] = "World" 9 | 10 | fmt.Println(a[0], a[1]) 11 | fmt.Println(a) 12 | } 13 | -------------------------------------------------------------------------------- /structs/range.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | var pow = []int{1,2,4,6,16,32,64,128} 6 | 7 | func main(){ 8 | 9 | for i, j := range pow{ 10 | fmt.Printf("2**%d = %d\n", i,j) 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /structs/slices.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main(){ 6 | p :=[]int{2, 3, 5, 7, 11, 13} 7 | 8 | fmt.Println(p) 9 | 10 | for i :=0; i < len(p); i++{ 11 | fmt.Printf("p[%d] == %d\n", i, p[i]) 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /structs/struct.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Vetex struct { 6 | X int 7 | Y int 8 | } 9 | 10 | func main(){ 11 | fmt.Println(Vetex{1, 2}) 12 | } 13 | -------------------------------------------------------------------------------- /wikipedia/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://github.com/go-br/estudos/tree/master/wikipedia 4 | 5 | import ( 6 | "encoding/json" 7 | "fmt" 8 | "io/ioutil" 9 | "net/http" 10 | "reflect" 11 | "strings" 12 | ) 13 | 14 | func main() { 15 | 16 | resp, err := http.Get("https://pt.wikipedia.org/w/api.php?action=opensearch&format=json&search=Go_(linguagem_de_programação)") 17 | 18 | if err != nil { 19 | fmt.Println(err) 20 | return 21 | } 22 | 23 | defer resp.Body.Close() 24 | 25 | body, err := ioutil.ReadAll(resp.Body) 26 | 27 | if err != nil { 28 | fmt.Println(err) 29 | } 30 | 31 | var m []interface{} 32 | 33 | err = json.Unmarshal(body, &m) 34 | 35 | if err != nil { 36 | fmt.Println(err) 37 | return 38 | } 39 | 40 | r := make(map[string]int) 41 | 42 | walker(m, r) 43 | 44 | for k, v := range r { 45 | fmt.Println(k, v) 46 | } 47 | } 48 | 49 | func walker(m interface{}, r map[string]int) { 50 | 51 | for _, v := range m.([]interface{}) { 52 | switch reflect.TypeOf(v).Kind() { 53 | case reflect.String: 54 | a := strings.Split(v.(string), " ") 55 | 56 | for _, s := range a { 57 | aux := r[s] 58 | aux++ 59 | r[s] = aux 60 | } 61 | case reflect.Slice: 62 | walker(v, r) 63 | default: 64 | fmt.Println(v, reflect.TypeOf(v)) 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /xml/pizza/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/xml" 5 | "fmt" 6 | "io/ioutil" 7 | "net/http" 8 | ) 9 | 10 | // RSS - 11 | type RSS struct { 12 | XMLName xml.Name `xml:"rss"` 13 | Version string `xml:"version,attr"` 14 | Title string `xml:"channel>title"` 15 | Link string `xml:"channel>link"` 16 | Description string `xml:"channel>description"` 17 | PubDate string `xml:"channel>pubDate"` 18 | ItemList []Item `xml:"channel>item"` 19 | } 20 | 21 | // Item - 22 | type Item struct { 23 | Title string `xml:"title"` 24 | Link string `xml:"link"` 25 | Description string `xml:"description"` 26 | Content string `xml:"encoded"` 27 | PubDate string `xml:"pubDate"` 28 | Comments string `xml:"comments"` 29 | } 30 | 31 | func main() { 32 | resp, err := http.Get("http://pizzadedados.com/feed.xml") 33 | 34 | if err != nil { 35 | fmt.Println(err) 36 | } 37 | 38 | body, err := ioutil.ReadAll(resp.Body) 39 | 40 | if err != nil { 41 | fmt.Println(err) 42 | } 43 | 44 | rss := RSS{} 45 | err = xml.Unmarshal(body, &rss) 46 | 47 | if err != nil { 48 | fmt.Println(err) 49 | } 50 | 51 | for k, i := range rss.ItemList { 52 | fmt.Println(k, i.Title) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /yml/example1/example.yml: -------------------------------------------------------------------------------- 1 | name: Henrique 2 | last_name: Lopes 3 | age: 35 4 | -------------------------------------------------------------------------------- /yml/example1/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | import ( 3 | "fmt" 4 | "log" 5 | "io/ioutil" 6 | "gopkg.in/yaml.v2" 7 | ) 8 | // People - 9 | type People struct { 10 | Name string `yaml:name"` 11 | LastName string `yaml:"last_name"` 12 | Age int `yaml:"age"` 13 | } 14 | 15 | func main(){ 16 | 17 | example, err := ioutil.ReadFile("example.yml") 18 | 19 | if err != nil { 20 | log.Println("Error to load example.yml") 21 | } 22 | 23 | p := People{} 24 | err = yaml.Unmarshal(example, &p) 25 | 26 | if err != nil { 27 | log.Println("Unmarshal error.") 28 | } 29 | 30 | fmt.Println(p) 31 | } 32 | -------------------------------------------------------------------------------- /yml/example2/example.yml: -------------------------------------------------------------------------------- 1 | name: Henrique 2 | last_name: Lopes 3 | age: 35 4 | -------------------------------------------------------------------------------- /yml/example2/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | import ( 3 | "fmt" 4 | "log" 5 | "io/ioutil" 6 | "github.com/smallfish/simpleyaml" 7 | ) 8 | 9 | func main(){ 10 | example, err := ioutil.ReadFile("example.yml") 11 | 12 | if err != nil { 13 | log.Println("Error to load example.yml") 14 | } 15 | 16 | yaml, err := simpleyaml.NewYaml(example) 17 | 18 | if err != nil { 19 | log.Println("NewYaml error.") 20 | } 21 | 22 | fmt.Println(yaml.Get("name").String()) 23 | fmt.Println(yaml.Get("last_name").String()) 24 | fmt.Println(yaml.Get("age").Int()) 25 | } 26 | -------------------------------------------------------------------------------- /yml/example3/example.yml: -------------------------------------------------------------------------------- 1 | people: 2 | name: "Henrique" 3 | last_name: "Lopes" 4 | age: 35 5 | hobbys: 6 | - music 7 | - woodwork 8 | - running 9 | -------------------------------------------------------------------------------- /yml/example3/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | import ( 3 | "fmt" 4 | "log" 5 | "io/ioutil" 6 | "gopkg.in/yaml.v2" 7 | ) 8 | 9 | 10 | // Yaml - 11 | type Yaml struct { 12 | data interface{} 13 | } 14 | 15 | func main(){ 16 | 17 | example, err := ioutil.ReadFile("example.yml") 18 | 19 | if err != nil { 20 | log.Println("Error to load example.yml") 21 | } 22 | 23 | var data interface{} 24 | err = yaml.Unmarshal(example, &data) 25 | 26 | if err != nil { 27 | log.Println("Unmarshal error.") 28 | } 29 | 30 | y := Yaml{data} 31 | fmt.Println(y) 32 | } 33 | --------------------------------------------------------------------------------