-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschema.go
61 lines (47 loc) · 1.15 KB
/
schema.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
package main
import (
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"sync"
"golang.org/x/sync/singleflight"
)
var errSchemaNotFound = errors.New("schema not found")
var (
schemaSingleFlightGroup singleflight.Group
schemaCache sync.Map
)
func getSchema(schemaURL string) ([]byte, error) {
schema, err, _ := schemaSingleFlightGroup.Do(schemaURL, func() (any, error) {
cache, ok := schemaCache.Load(schemaURL)
if ok {
log.Printf("Load schema from cache: %s", schemaURL)
return cache.([]byte), nil
}
log.Printf("Load schema from GitHub: %s", schemaURL)
resp, err := client.Get(schemaURL)
if err != nil {
return nil, fmt.Errorf("client.Get: %w", err)
}
defer resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK:
case http.StatusNotFound:
return nil, errSchemaNotFound
default:
return nil, fmt.Errorf("client.Get: StatusCode: %d", resp.StatusCode)
}
schema, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("ioutil.ReadAll: %w", err)
}
schemaCache.Store(schemaURL, schema)
return schema, nil
})
if err != nil {
return nil, err
}
return schema.([]byte), nil
}