-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
84 lines (70 loc) · 1.98 KB
/
main.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
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/jellydator/ttlcache/v2"
"log"
"net/http"
v1 "stock/pkg/api/openfoodwatch/v1"
"stock/pkg/rest"
"strings"
"time"
)
const (
listen = ""
port = 8081
offBaseUrl = "https://de.openfoodfacts.org"
ttl = 336 * time.Hour
)
func main() {
var cache ttlcache.SimpleCache = ttlcache.NewCache()
err := cache.SetTTL(ttl)
if err != nil {
log.Fatalf("Could not set cache TTL to %d hours because %v", ttl/time.Hour, err)
}
AddHandlers(cache)
StartServer(port, listen)
}
func AddHandlers(cache ttlcache.SimpleCache) {
offClient := v1.NewForOpts(rest.WithBaseURL(offBaseUrl), rest.WithCache(cache))
http.HandleFunc("/categories", func(w http.ResponseWriter, r *http.Request) {
resp, err := offClient.Categories().List(context.Background())
HandleError(w, err)
WriteJsonSuccess(w, resp)
})
http.HandleFunc("/category/", func(w http.ResponseWriter, r *http.Request) {
id := strings.TrimPrefix(r.URL.Path, "/category/")
//page := r.URL.Query().Get("page")
resp, err := offClient.Products().GetForCategory(context.Background(), id)
HandleError(w, err)
WriteJsonSuccess(w, resp)
})
http.HandleFunc("/products/", func(w http.ResponseWriter, r *http.Request) {
id := strings.TrimPrefix(r.URL.Path, "/products/")
resp, err := offClient.Products().Get(context.Background(), id)
HandleError(w, err)
WriteJsonSuccess(w, resp)
})
}
func StartServer(port int, listen string) {
base := fmt.Sprintf("%s:%d", listen, port)
fmt.Println(base)
if err := http.ListenAndServe(base, nil); err != nil {
log.Fatalln(err)
}
}
func WriteJsonSuccess(w http.ResponseWriter, response interface{}) {
WriteJson(w, response)
}
func WriteJson(w http.ResponseWriter, response interface{}) {
data, _ := json.Marshal(response)
w.Header().Add("Content-Type", "application/json")
fmt.Fprint(w, string(data))
}
func HandleError(w http.ResponseWriter, err error) {
if err != nil {
log.Println(err)
w.WriteHeader(500)
}
}