-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
78 lines (59 loc) · 1.61 KB
/
server.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"strings"
)
func getProductHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)
return
}
apiKey := r.URL.Query().Get("key")
usage, err := getUsage(apiKey)
if err != nil {
http.Error(w, "Invalid API key.", http.StatusUnauthorized)
return
}
asin := strings.TrimPrefix(r.URL.Path, "/product/")
if len(asin) != 10 {
http.Error(w, "Invalid ASIN.", 400)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Usage", strconv.Itoa(usage+1))
dataChannel := make(chan ProductData, 1)
assignDataRequest(asin, dataChannel)
productData := <-dataChannel
response, _ := json.Marshal(productData)
fmt.Fprint(w, string(response))
go incrementUsage(apiKey)
}
func getUsageHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)
return
}
apiKey := r.URL.Query().Get("key")
usage, err := getUsage(apiKey)
if err != nil {
http.Error(w, "Invalid API key.", 401)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, "{\n \"key\": \""+apiKey+"\",\n \"requests\": "+strconv.Itoa(usage)+"\n}")
}
func handleRequests() {
port := ":" + os.Getenv("PORT")
if port == ":" {
port = ":8080"
}
http.HandleFunc("/product/", getProductHandler)
http.HandleFunc("/usage", getUsageHandler)
http.Handle("/", http.FileServer(http.Dir("./static")))
http.ListenAndServe(port, nil)
}