Skip to content

Commit

Permalink
Refactoring ViaCep data lookup to improve modularity
Browse files Browse the repository at this point in the history
[EN]

This commit re-organizes `BuscaCep` code into different packages. The main goal was to improve code modularity by separating responsibilities and making code easier to test.

The `ViaCep` struct and `BuscaCep` function were moved from `main.go` into a new file, `domain/viacep.go`. This file now encapsulates functionality related to fetching and checking `ViaCep` data.

Similarly, the `BuscaCepHandle` function was moved to a new file, `handlers/cep.go`. This file now handles the HTTP request/response flow for CEP (Postal Code) searches.

Two new test files `domain/viacep_test.go` and `handlers/cep_test.go` were also created, laying the groundwork for future test cases.

[PT-BR]

Refatorando a pesquisa de dados do ViaCep para melhorar a modularidade

Este commit reorganiza o código `BuscaCep` em pacotes diferentes. O principal objetivo era melhorar a modularidade do código, separando responsabilidades e tornando o código mais fácil de testar.

A estrutura `ViaCep` e a função `BuscaCep` foram movidas de `main.go` para um novo arquivo, `domain/viacep.go`. Este arquivo agora encapsula funcionalidades relacionadas à busca e verificação de dados do `ViaCep`.

Da mesma forma, a função `BuscaCepHandle` foi movida para um novo arquivo, `handlers/cep.go`. Este arquivo agora trata do fluxo de solicitação/resposta HTTP para pesquisas CEP (Código Postal).

Dois novos arquivos de teste `domain/viacep_test.go` e `handlers/cep_test.go` também foram criados, estabelecendo as bases para futuros casos de teste.
  • Loading branch information
marcelomatz committed Aug 31, 2023
1 parent 00daa41 commit 78a2fc9
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 71 deletions.
73 changes: 2 additions & 71 deletions Main.go
Original file line number Diff line number Diff line change
@@ -1,84 +1,15 @@
package main

import (
"encoding/json"
"fmt"
"io"
"http_buscaCep/handlers"
"net/http"
)

type ViaCep struct {
Cep string `json:"cep"`
Logradouro string `json:"logradouro"`
Bairro string `json:"bairro"`
Localidade string `json:"localidade"`
Uf string `json:"uf"`
Ibge string `json:"ibge"`
Gia string `json:"gia"`
Ddd string `json:"ddd"`
Siafi string `json:"siafi"`
}

// isEmpty retorna true se todas as propriedades da estrutura ViaCep estiverem vazias
func (v ViaCep) isEmpty() bool {
return v.Cep == "" && v.Logradouro == "" && v.Bairro == "" && v.Localidade == "" && v.Uf == "" && v.Ibge == "" && v.Gia == "" && v.Ddd == "" && v.Siafi == ""
}

func main() {
http.HandleFunc("/", BuscaCepHandle)
http.HandleFunc("/", handlers.BuscaCepHandle)
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Printf("ListenAndServe error: %v", err)
}
}

func BuscaCepHandle(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
cepParam := r.URL.Query().Get("cep")
if cepParam == "" || len(cepParam) != 8 {
http.Error(w, "Invalid cep parameter", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
viaCep, err := BuscaCep(cepParam)
if err != nil {
http.Error(w, fmt.Sprintf("Error getting CEP details: %v", err), http.StatusInternalServerError)
return
}
if viaCep.isEmpty() {
http.Error(w, "CEP not found", http.StatusNotFound)
return
}
err = json.NewEncoder(w).Encode(viaCep)
if err != nil {
http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
return
}
}

func BuscaCep(cep string) (*ViaCep, error) {
url := "https://viacep.com.br/ws/" + cep + "/json/"
resp, err := http.Get(url)
if err != nil {
return nil, fmt.Errorf("HTTP request error: %w", err)
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {

}
}(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("reading body error: %w", err)
}
var viaCep ViaCep
err = json.Unmarshal(body, &viaCep)
if err != nil {
return nil, fmt.Errorf("JSON unmarshalling error: %w", err)
}
return &viaCep, nil
}
52 changes: 52 additions & 0 deletions domain/viacep.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package domain

import (
"encoding/json"
"fmt"
"io"
"net/http"
)

type ViaCep struct {
Cep string `json:"cep"`
Logradouro string `json:"logradouro"`
Bairro string `json:"bairro"`
Localidade string `json:"localidade"`
Uf string `json:"uf"`
Ibge string `json:"ibge"`
Gia string `json:"gia"`
Ddd string `json:"ddd"`
Siafi string `json:"siafi"`
}

// isEmpty retorna true se todas as propriedades da estrutura ViaCep estiverem vazias
func (v ViaCep) isEmpty() bool {
return v.Cep == "" && v.Logradouro == "" && v.Bairro == "" && v.Localidade == "" && v.Uf == "" && v.Ibge == "" && v.Gia == "" && v.Ddd == "" && v.Siafi == ""
}

func BuscaCep(cep string) (*ViaCep, error) {
url := "https://viacep.com.br/ws/" + cep + "/json/"
resp, err := http.Get(url)
if err != nil {
return nil, fmt.Errorf("HTTP request error: %w", err)
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {

}
}(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("reading body error: %w", err)
}
var viaCep ViaCep
err = json.Unmarshal(body, &viaCep)
if err != nil {
return nil, fmt.Errorf("JSON unmarshalling error: %w", err)
}
if viaCep.isEmpty() {
return nil, fmt.Errorf("CEP %s not found", cep)
}
return &viaCep, nil
}
1 change: 1 addition & 0 deletions domain/viacep_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package domain
31 changes: 31 additions & 0 deletions handlers/cep.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package handlers

import (
"encoding/json"
"fmt"
"http_buscaCep/domain"
"net/http"
)

func BuscaCepHandle(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
cepParam := r.URL.Query().Get("cep")
if cepParam == "" || len(cepParam) != 8 {
http.Error(w, "Invalid cep parameter", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
viaCep, err := domain.BuscaCep(cepParam)
if err != nil {
http.Error(w, fmt.Sprintf("Error getting CEP details: %v", err), http.StatusInternalServerError)
return
}
err = json.NewEncoder(w).Encode(viaCep)
if err != nil {
http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
return
}
}
1 change: 1 addition & 0 deletions handlers/cep_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package handlers

0 comments on commit 78a2fc9

Please sign in to comment.