Last active
March 18, 2024 12:58
-
-
Save richhh7g/309a7b201efd7709a30df00869a8a1ec to your computer and use it in GitHub Desktop.
Go Lang - Search CEP
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
// go run search_cep.go 00000000 | |
// Or | |
// go build search_cep.go | |
// ./search_cep 00000000 | |
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io" | |
"net/http" | |
"os" | |
) | |
type Address struct { | |
CEP string `json:"cep"` | |
State string `json:"uf"` | |
Street string `json:"logradouro"` | |
District string `json:"localidade"` | |
Complement string `json:"complemento"` | |
} | |
func toAddress(res []byte) (Address, error) { | |
var address Address | |
err := json.Unmarshal(res, &address) | |
if err != nil { | |
return Address{}, fmt.Errorf("Não foi possivel converter o JSON para Address.") | |
} | |
return address, nil | |
} | |
func GetCEP(cep string) (Address, error) { | |
const baseUrl = "https://viacep.com.br/ws/" | |
url := fmt.Sprintf("%s%s/json", baseUrl, cep) | |
req, err := http.Get(url) | |
if err != nil { | |
return Address{}, fmt.Errorf("Não foi possivel fazer a requisição HTTP.") | |
} | |
defer req.Body.Close() | |
res, err := io.ReadAll(req.Body) | |
if err != nil { | |
return Address{}, fmt.Errorf("Não foi possivel ler a resposta da requisição HTTP.") | |
} | |
address, err := toAddress(res) | |
if err != nil { | |
return Address{}, err | |
} | |
return address, nil | |
} | |
func main() { | |
if len(os.Args) < 2 { | |
fmt.Println("Por favor, insira um CEP como argumento.") | |
return | |
} | |
cep := os.Args[1] | |
result, err := GetCEP(cep) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
fmt.Println("CEP:", result.CEP) | |
fmt.Println("Estado:", result.State) | |
fmt.Println("Rua:", result.Street) | |
fmt.Println("Bairro:", result.District) | |
fmt.Println("Complemento:", result.Complement) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment