-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathserver.go
153 lines (132 loc) · 3.29 KB
/
server.go
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/gorilla/context"
"github.com/gorilla/mux"
"github.com/ryanuber/go-filecache"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
)
const serverPort = "3000";
const cacheTime = 500;
type Cep 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"`
Unidade string `json:"unidade"`
Ibge string `json:"ibge"`
Gia string `json:"gia"`
}
func main() {
errorMessage := "Erro lendo CEP"
router := mux.NewRouter()
router.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
_, err := rw.Write([]byte([]byte("ping")))
if err != nil {
respondWithError(rw, http.StatusUnauthorized, err.Error(), errorMessage)
return
}
})
router.HandleFunc("/cep/{id}", func(rw http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
rw.Header().Set("Content-Type", "application/json")
cep, err := getCep(vars["id"])
if err != nil {
respondWithError(rw, http.StatusUnauthorized, err.Error(), errorMessage)
return
}
_, err = rw.Write([]byte(cep))
if err != nil {
respondWithError(rw, http.StatusUnauthorized, err.Error(), errorMessage)
return
}
})
http.Handle("/", router)
logger := log.New(os.Stderr, "logger: ", log.Lshortfile)
srv := &http.Server{
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
Addr: ":"+serverPort,
Handler: context.ClearHandler(http.DefaultServeMux),
ErrorLog: logger,
}
err := srv.ListenAndServe()
if err != nil {
panic(err)
}
}
func getCep(id string) (string, error) {
cached := getFromCache(id)
if cached != "" {
return cached, nil
}
req, err := http.Get(fmt.Sprintf("http://viacep.com.br/ws/%s/json/", id))
if err != nil {
return "", err
}
var c Cep
err = json.NewDecoder(req.Body).Decode(&c)
if err != nil {
return "", err
}
res, err := json.Marshal(c)
if err != nil {
return "", err
}
return saveOnCache(id, string(res)), nil
}
func getFromCache(id string) string {
updater := func(path string) error {
return errors.New("expired")
}
fc := filecache.New(getCacheFilename(id), cacheTime*time.Second, updater)
fh, err := fc.Get()
if err != nil {
return ""
}
content, err := ioutil.ReadAll(fh)
if err != nil {
return ""
}
return string(content)
}
func saveOnCache(id string, content string) string {
updater := func(path string) error {
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
_, err = f.Write([]byte(content))
return err
}
fc := filecache.New(getCacheFilename(id), cacheTime*time.Second, updater)
_, err := fc.Get()
if err != nil {
return ""
}
return content
}
func getCacheFilename(id string) string {
return os.TempDir()+"/cep"+strings.Replace(id, "-", "", -1)
}
//RespondWithError return a http error
func respondWithError(w http.ResponseWriter, code int, e string, message string) {
respondWithJSON(w, code, map[string]string{"code": strconv.Itoa(code), "error": e, "message": message})
}
func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}