forked from liuzl/et
-
Notifications
You must be signed in to change notification settings - Fork 0
/
easy_api.go
53 lines (47 loc) · 996 Bytes
/
easy_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
package et
import (
"encoding/json"
"io/ioutil"
"sync"
)
type parsers struct {
sync.Mutex
items map[string]*Parser
}
func (p *parsers) get(fname string, refresh bool) (*Parser, error) {
p.Lock()
defer p.Unlock()
if !refresh && p.items[fname] != nil {
return p.items[fname], nil
}
content, err := ioutil.ReadFile(fname)
if err != nil {
return nil, err
}
parser := new(Parser)
if err := json.Unmarshal(content, parser); err != nil {
return nil, err
}
p.items[fname] = parser
return parser, nil
}
var pool = &parsers{items: make(map[string]*Parser)}
func Parse(fname, url, page string) ([]map[string]interface{}, error) {
p, err := pool.get(fname, false)
if err != nil {
return nil, err
}
_, ret, err := p.Parse(page, url)
return ret, err
}
func ParseExt(fname, url, page string) (string, error) {
ret, err := Parse(fname, url, page)
if err != nil {
return "", err
}
b, err := json.Marshal(ret)
if err != nil {
return "", err
}
return string(b), nil
}