-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
74 lines (62 loc) · 1.42 KB
/
app.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
// Sample helloworld is an App Engine app.
package main
// [START import]
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strings"
sdk "github.com/fodmap-diet/go-sdk"
)
func main() {
http.HandleFunc("/search/", searchHandler)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
log.Printf("Defaulting to port %s", port)
}
log.Printf("Listening on port %s", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}
// searchHandler responds to a item search request
func searchHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/search/" {
http.NotFound(w, r)
return
}
keys, ok := r.URL.Query()["item"]
if !ok {
log.Println("Url Param 'item' is missing")
http.Error(w, "Url Param 'item' is missing", http.StatusBadRequest)
return
}
items := make(map[string]interface{})
for _, key := range keys {
key = strings.ToLower(key)
if len(key) == 0 {
log.Println("Invalid item")
http.Error(w, "Invalid item", http.StatusBadRequest)
return
}
item, err := sdk.SearchItem(key)
if err != nil {
items[key] = struct {
Error string `json: "error"`
}{
err.Error(),
}
continue
}
items[key] = item
}
js, err := json.MarshalIndent(items, "", " ")
if err != nil {
log.Println(err.Error())
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}