-
Notifications
You must be signed in to change notification settings - Fork 0
/
cotacao-mux-rest-api.go
73 lines (57 loc) · 1.59 KB
/
cotacao-mux-rest-api.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
package main
import (
"github.com/gorilla/mux"
"net/http"
"fmt"
"log"
"encoding/json"
"regexp"
"errors"
"io"
"bytes"
)
const cotacaoEndpoint = "https://ptax.bcb.gov.br/ptax_internet/consultarUltimaCotacaoDolar.do"
type cotacao struct {
Compra string `json:"compra,omitempty"`
Venda string `json:"venda,omitempty"`
}
func main() {
router := mux.NewRouter().StrictSlash(true)
sub := router.PathPrefix("/api/v1").Subrouter()
sub.HandleFunc("/info", hello).Methods("GET")
sub.HandleFunc("/cotacao", getCotacao).Methods("GET")
fmt.Println("Initializing server...")
log.Fatal(http.ListenAndServe(":3000", router))
}
func hello(writer http.ResponseWriter, request *http.Request) {
writer.Write([]byte("API para retornar a cotação do Dolar."))
}
func getCotacao(writer http.ResponseWriter, request *http.Request) {
content := retornaCotacaoEndpoint()
cotacao := formatResponse(content)
writer.Header().Set("Content-Type", "application/json")
json.NewEncoder(writer).Encode(cotacao)
}
func retornaCotacaoEndpoint() (content []byte) {
response, err := http.Get(cotacaoEndpoint)
checkError(err)
defer response.Body.Close()
var buffer bytes.Buffer
io.Copy(&buffer, response.Body)
return buffer.Bytes()
}
func formatResponse(content []byte) (value cotacao) {
regex := regexp.MustCompile("[1-9],[0-9][0-9][0-9][0-9]")
valores := regex.FindAll(content, -1)
if len(valores) == 2 {
value = cotacao{string(valores[0][:]), string(valores[1][:])}
} else {
panic(errors.New("não foi possivel encontrar valores"))
}
return
}
func checkError(err error) {
if err != nil {
panic(err)
}
}