Skip to content

Get Address - Basic API

Help: JSON-to-Go

run command
cd src/projectapi/
go run main.go
curl localhost:8080/get-address?zipcode=08295005
curl localhost:8080/get-address?zipcode=03087000
curl localhost:8080/get-address?zipcode=17509180
package address

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

type Address struct {
    ZipCode     string `json:"cep"`
    PublicPlace string `json:"logradouro"`
    Extra       string `json:"complemento"`
    District    string `json:"bairro"`
    City        string `json:"localidade"`
    State       string `json:"uf"`
    Ibge        string `json:"ibge"`
    Gia         string `json:"gia"`
    Ddd         string `json:"ddd"`
    Siafi       string `json:"siafi"`
}

func GetAddress(zipcode string) (*Address, error) {
    url := "https://viacep.com.br/ws/" + zipcode + "/json"
    req, err := http.Get(url)
    if err != nil {
        return nil, err
    }
    defer req.Body.Close()
    res, _ := io.ReadAll(req.Body)
    var address Address
    err = json.Unmarshal(res, &address)
    if err != nil {
        return nil, err
    }
    return &address, nil
}
package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"

    "example.com/api.project/address"
)

func setHeaders(next http.Handler) http.Handler {
    return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
        res.Header().Set("Content-Type", "application/json")
        next.ServeHTTP(res, req)
    })
}

func GetAddressHandler(res http.ResponseWriter, req *http.Request) {
    queryData := req.URL.Query()
    if !queryData.Has("zipcode") {
        res.WriteHeader(http.StatusBadRequest)
        return
    }
    zipCodeParam := req.URL.Query().Get("zipcode")
    address, error := address.GetAddress(zipCodeParam)
    if error != nil {
        res.WriteHeader(http.StatusInternalServerError)
        return
    }
    res.WriteHeader(http.StatusOK)
    json.NewEncoder(res).Encode(address)
}

func main() {
    mux := http.NewServeMux()

    mux.HandleFunc("/get-address", GetAddressHandler)
    mux_wrapped := setHeaders(mux)

    server := &http.Server{
        Addr:    ":8080",
        Handler: mux_wrapped,
    }

    fmt.Println("Server is listening on port 8080")
    if err := server.ListenAndServe(); err != nil {
        log.Fatal(err)
    }
}
output
{"cep":"08295-005","logradouro":"Avenida Miguel Ignácio Curi","complemento":"","bairro":"Vila Carmosina","localidade":"São Paulo","uf":"SP","ibge":"3550308","gia":"1004","ddd":"11","siafi":"7107"}
{"cep":"03087-000","logradouro":"Rua São Jorge","complemento":"","bairro":"Parque São Jorge","localidade":"São Paulo","uf":"SP","ibge":"3550308","gia":"1004","ddd":"11","siafi":"7107"}
{"cep":"17509-180","logradouro":"Avenida Vicente Ferreira","complemento":"até 470/471","bairro":"Marília","localidade":"Marília","uf":"SP","ibge":"3529005","gia":"4388","ddd":"14","siafi":"6681"}