-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
65 lines (60 loc) · 1.37 KB
/
main.go
File metadata and controls
65 lines (60 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
type ViaCep struct {
Cep string `json:"cep"`
Logradouro string `json:"logradouro"`
Complemento string `json:"complemento"`
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"`
}
func main() {
http.HandleFunc("/", BuscaCepHandler)
http.ListenAndServe(":8080", nil)
fmt.Println("")
}
func BuscaCepHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
w.WriteHeader(http.StatusNotFound)
return
}
cepParam := r.URL.Query().Get("cep")
if cepParam == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
cep, error := BuscaCep(cepParam)
if error != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(cep)
}
func BuscaCep(cep string) (*ViaCep, error) {
resp, error := http.Get("https://viacep.com.br/ws/" + cep + "/json/")
if error != nil {
return nil, error
}
defer resp.Body.Close()
body, error := io.ReadAll(resp.Body)
if error != nil {
return nil, error
}
var c ViaCep
error = json.Unmarshal(body, &c)
if error != nil {
return nil, error
}
return &c, nil
}