-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactoring ViaCep data lookup to improve modularity
[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
1 parent
00daa41
commit 78a2fc9
Showing
5 changed files
with
87 additions
and
71 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
package domain |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
package handlers |