-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
50 lines (41 loc) · 1.02 KB
/
handlers.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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
// Index handle requests to "/"
func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello Friends!")
}
// CarbsIndex handle requests to "/carbs"
func CarbsIndex(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Usage: GET /carbs/:id for nutrition info")
}
// CarbsOne handle requests to "/carbs/:id"
func CarbsOne(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
ndbID := vars["ndbID"]
url := nutrientURL + "&ndbno=" + ndbID
log.Println(url)
resp, err := http.Get(url)
if err != nil {
log.Println(float64(resp.StatusCode) / 200)
panic(err)
}
if float64(resp.StatusCode)/200 > 1.495 {
http.Error(w, "Could not connect to Nutrient DB", http.StatusInternalServerError)
return
}
var n NutrientAPIResponse
json.NewDecoder(resp.Body).Decode(&n)
if err != nil {
panic(err)
}
var response = n.transform()
if err := json.NewEncoder(w).Encode(response); err != nil {
panic(err)
}
}