/
api.go
127 lines (111 loc) · 3.4 KB
/
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
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
package main
import (
"log"
"net/http"
"encoding/xml"
"github.com/pquerna/ffjson/ffjson"
"io/ioutil"
"github.com/gorilla/mux"
_ "github.com/go-sql-driver/mysql"
"github.com/patrickmn/go-cache"
"database/sql"
"sync"
"strings"
"time"
"runtime"
)
type Data struct {
ID string
Path string
}
type Bk struct{
Name string `json:"a"`
}
type Result struct {
Value []float64 `xml:"a>b>c"`
Routing string `xml:"d"`
}
type Resp struct {
ID string `json:"a"`
Flow int `json:"b"`
BkName string `json:"c"`
}
type Respslice struct {
Resps []Resp `json:"a"`
}
var ch *cache.Cache
var db *sql.DB
func computationWork(wg *sync.WaitGroup, data Data, c chan Resp) {
wg.Done()
t := Result{}
b:= Bk{}
data1, _ := ioutil.ReadFile(data.Path)
_ = xml.Unmarshal(data1, &t)
done := make(chan bool)
go func() {
r1, _ := http.Get("https://some-api.ext/"+t.Routing)
body, _ := ioutil.ReadAll(r1.Body)
_ = ffjson.Unmarshal(body, &b)
done <- true
}()
var total float64 = 0.00
for _, amount := range t.Value{
total += amount
}
<-done
c <- Resp{ID: data.ID, Flow: int(total), BkName: b.Name}
stmt, _ := db.Prepare("update DB.table set val1=?, val2=? where `id`=?")
_, _ = stmt.Exec(int(total), b.Name, data.ID)
}
func main() {
runtime.GC()
ch = cache.New(5*time.Minute, 30*time.Second)
db, _ = sql.Open("mysql", "root:password@tcp(hostname)/")
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", Index)
log.Fatal(http.ListenAndServe(":9797", router))
}
func Index(w http.ResponseWriter, r *http.Request) {
wg := sync.WaitGroup{}
data := Data{}
var res Respslice
var c chan Resp = make(chan Resp)
var temp Resp
var keyString string
keys := r.URL.Query().Get("key")
if len(keys) != 0 {
tmp:= strings.Split(keys, ",")
for _,element := range tmp {
val, found := ch.Get(element)
if !found {
keyString+= `'`+element+`'`
continue
}
data.ID = element
data.Path = val.(string)
wg.Add(1)
go computationWork(&wg, data, c)
temp = <-c
res.Resps = append(res.Resps, temp)
}
if len(keyString) != 0 {
keyString= strings.Replace(keyString, `''`, `','`, -1)
// keyString= `'`+strings.Replace(keys, `,`,`','`,-1)+`'`
rows, _ := db.Query("SELECT `id`, `file_name` FROM DB.table WHERE `id` IN ("+ keyString +")")
defer rows.Close()
for rows.Next() {
_ = rows.Scan(&data.ID, &data.Path)
ch.Set(data.ID, data.Path, cache.DefaultExpiration)
wg.Add(1)
go computationWork(&wg, data, c)
temp = <-c
res.Resps = append(res.Resps, temp)
}
}
wg.Wait()
b, _ := ffjson.Marshal(res)
w.Header().Set("Content-Type", "application/json")
w.Write(b)
// ffjson.Pool(b)
}
}