Skip to content

Commit

Permalink
Improve error handling & reporting in Main.go
Browse files Browse the repository at this point in the history
This commit enhances error handling in several parts of the Main.go file. Previously, the code simply returned when an error occurred. The update now outputs more useful error messages via fmt and http.Error, specifically noting the nature of the error that occurred. Not only does this achieve better transparency, it also helps to narrow down problems in future debugging scenarios.

[PT-BR]
Melhorar o tratamento de erros e relatórios no Main.go

Esse commit aprimora o tratamento de erros em várias partes do arquivo Main.go. Anteriormente, o código simplesmente retornava quando ocorria um erro. A atualização agora gera mensagens de erro mais úteis via fmt e http.Error, observando especificamente a natureza do erro que ocorreu. Isso não apenas alcança uma melhor transparência, mas também ajuda a reduzir os problemas em cenários de depuração futuros.
  • Loading branch information
marcelomatz committed Aug 31, 2023
1 parent 112b1df commit bddc551
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions Main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"encoding/json"
"fmt"
"io"
"net/http"
)
Expand All @@ -23,49 +24,53 @@ func main() {
http.HandleFunc("/", BuscaCepHandle)
err := http.ListenAndServe(":8080", nil)
if err != nil {
return
fmt.Printf("ListenAndServe error: %v", err)
}
}

func BuscaCepHandle(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
w.WriteHeader(http.StatusNotFound)
http.NotFound(w, r)
return
}
cepParam := r.URL.Query().Get("cep")
if cepParam == "" || len(cepParam) != 8 {
w.WriteHeader(http.StatusBadRequest)
http.Error(w, "Invalid cep parameter", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
viaCep, err := BuscaCep(cepParam)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
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
}

}

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

}
}(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
return nil, fmt.Errorf("Reading body error: %w", err)
}
var viaCep ViaCep
err = json.Unmarshal(body, &viaCep)
if err != nil {
return nil, err
return nil, fmt.Errorf("JSON unmarshalling error: %w", err)
}
return &viaCep, nil
}

0 comments on commit bddc551

Please sign in to comment.