/
main.go
381 lines (346 loc) · 9.69 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package main
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"io"
"math"
"microservice/helpers"
"microservice/src"
"net/http"
"sort"
"strconv"
"sync"
)
type Patient struct {
age int
weightKg float64
heightCm float64
gender string
physicalActivity float64
expectedCalories float64
}
type Meal struct {
name string
percent float64
category string
}
func FindMax(products []Recipe) []Recipe {
max := products[0]
for _, product := range products {
if product.Calories > max.Calories {
max = product
}
}
var recipe []Recipe
recipe = append(recipe, max)
return recipe
}
type SubNutrient struct {
Label string `json:"label"`
Tag string `json:"tag"`
SchemaOrgTag string `json:"schemaOrgTag"`
Total float64 `json:"total"`
HasRDI bool `json:"hasRDI"`
Daily float64 `json:"daily"`
Unit string `json:"unit"`
}
type ResponseRecipe struct {
Uri string `json:"uri"`
Label string `json:"label"`
Image string `json:"image"`
Images struct {
THUMBNAIL struct {
Url string `json:"url"`
Width float64 `json:"width"`
Height float64 `json:"height"`
} `json:"THUMBNAIL"`
SMALL struct {
Url string `json:"url"`
Width float64 `json:"width"`
Height float64 `json:"height"`
} `json:"SMALL"`
REGULAR struct {
Url string `json:"url"`
Width float64 `json:"width"`
Height float64 `json:"height"`
} `json:"REGULAR"`
LARGE struct {
Url string `json:"url"`
Width float64 `json:"width"`
Height float64 `json:"height"`
} `json:"LARGE"`
} `json:"images"`
Source string `json:"source"`
Url string `json:"url"`
ShareAs string `json:"shareAs"`
Yield float64 `json:"yield"`
DietLabels []string `json:"dietLabels"`
HealthLabels []string `json:"healthLabels"`
Cautions []string `json:"cautions"`
IngredientLines []string `json:"ingredientLines"`
Calories float64 `json:"calories"`
GlycemicIndex float64 `json:"glycemicIndex"`
TotalCO2Emissions float64 `json:"totalCO2Emissions"`
Co2EmissionsClass string `json:"co2EmissionsClass"`
TotalWeight float64 `json:"totalWeight"`
MealType []string `json:"mealType"`
Ingredients []src.Food
}
type Recipe struct {
Uri string `json:"uri"`
Label string `json:"label"`
Image string `json:"image"`
Images struct {
THUMBNAIL struct {
Url string `json:"url"`
Width float64 `json:"width"`
Height float64 `json:"height"`
} `json:"THUMBNAIL"`
SMALL struct {
Url string `json:"url"`
Width float64 `json:"width"`
Height float64 `json:"height"`
} `json:"SMALL"`
REGULAR struct {
Url string `json:"url"`
Width float64 `json:"width"`
Height float64 `json:"height"`
} `json:"REGULAR"`
LARGE struct {
Url string `json:"url"`
Width float64 `json:"width"`
Height float64 `json:"height"`
} `json:"LARGE"`
} `json:"images"`
Source string `json:"source"`
Url string `json:"url"`
ShareAs string `json:"shareAs"`
Yield float64 `json:"yield"`
DietLabels []string `json:"dietLabels"`
HealthLabels []string `json:"healthLabels"`
Cautions []string `json:"cautions"`
IngredientLines []string `json:"ingredientLines"`
Ingredients []struct {
Text string `json:"text"`
Quantity float64 `json:"quantity"`
Measure string `json:"measure"`
Food string `json:"food"`
Weight float64 `json:"weight"`
FoodId string `json:"foodId"`
} `json:"ingredients"`
Calories float64 `json:"calories"`
GlycemicIndex float64 `json:"glycemicIndex"`
TotalCO2Emissions float64 `json:"totalCO2Emissions"`
Co2EmissionsClass string `json:"co2EmissionsClass"`
TotalWeight float64 `json:"totalWeight"`
CuisineType []string `json:"cuisineType"`
MealType []string `json:"mealType"`
DishType []string `json:"dishType"`
Instructions []string `json:"instructions"`
Tags []string `json:"tags"`
ExternalId string `json:"externalId"`
TotalNutrients struct {
} `json:"totalNutrients"`
TotalDaily struct {
} `json:"totalDaily"`
Digest []struct {
Label string `json:"label"`
Tag string `json:"tag"`
SchemaOrgTag string `json:"schemaOrgTag"`
Total float64 `json:"total"`
HasRDI bool `json:"hasRDI"`
Daily float64 `json:"daily"`
Unit string `json:"unit"`
SubNutrients []SubNutrient `json:"sub"`
} `json:"digest"`
}
type RecipeStruct struct {
From int `json:"from"`
To int `json:"to"`
Count int `json:"count"`
Links struct {
Self struct {
Href string `json:"href"`
Title string `json:"title"`
} `json:"self"`
Next struct {
Href string `json:"href"`
Title string `json:"title"`
} `json:"next"`
} `json:"_links"`
Hits []struct {
Recipe Recipe `json:"recipe"`
Links struct {
Self struct {
Href string `json:"href"`
Title string `json:"title"`
} `json:"self"`
Next struct {
Href string `json:"href"`
Title string `json:"title"`
} `json:"next"`
} `json:"_links"`
} `json:"hits"`
}
func fetchRecipes(url string, results chan<- []Recipe, wg *sync.WaitGroup, calories float64) {
defer wg.Done()
response, err := http.Get(url)
if err != nil {
fmt.Println("Error making request:", err)
return
}
defer response.Body.Close()
var recipe RecipeStruct
body, err := io.ReadAll(response.Body)
if err != nil {
fmt.Printf("Error reading response body for %s: \n", err)
return
}
err = json.Unmarshal(body, &recipe)
if err != nil {
fmt.Printf("Error parsing JSON for %s: \n", err)
return
}
caloriesPerMeal := calories + 0.1*calories
var recipes []Recipe
flag := 3
for _, v := range recipe.Hits {
if v.Recipe.Calories <= caloriesPerMeal {
if flag != 0 {
recipes = append(recipes, v.Recipe)
flag--
continue
}
break
}
}
results <- FindMax(recipes)
}
func searchProduct(query string, wgi *sync.WaitGroup, results chan<- src.Food) {
defer wgi.Done()
response, err := http.Get("https://api.edamam.com/api/food-database/v2/parser?app_id=e3a6a808&app_key=44af244f2f5233960f919629f8f7dfcf&ingr=" + query)
if err != nil {
fmt.Println("Error making request:", err)
return
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
fmt.Printf("Error reading response body for %s: \n", err)
return
}
var data src.JSONData
err = json.Unmarshal(body, &data)
if err != nil {
return
}
if len(data.Hints) > 0 {
results <- data.Hints[0].Food
}
}
func Recipes(ctx *gin.Context) {
var wg sync.WaitGroup
param := ctx.Param("calories")
calories, _ := strconv.ParseFloat(param, 8)
if calories <= 500 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "Min 500 calories"})
return
}
results := make(chan []Recipe)
var meals []Meal
meals = append(meals,
Meal{
name: "Breakfast",
percent: 20,
category: "&dishType=Cereals&dishType=Pancake&dishType=Sandwiches",
},
Meal{
name: "Lunch",
percent: 20,
category: "&dishType=Soup",
},
Meal{
name: "Lunch",
percent: 20,
category: "&dishType=Main%20course",
},
Meal{
name: "Dinner",
percent: 20,
})
for _, meal := range meals {
wg.Add(1)
caloriesPerMeal := helpers.CalculateValueFromPercent(calories, meal.percent)
go fetchRecipes("https://api.edamam.com/api/recipes/v2?type=public&app_id=229871f5&app_key=2fbe0ee7d7b5857a57e48e6f58232deb&health=alcohol-free&cuisineType=Central%20Europe&calories=10-"+fmt.Sprintf("%v", math.Round(caloriesPerMeal+0.1*caloriesPerMeal))+"&mealType="+meal.name+meal.category+"&co2EmissionsClass=B&random=true", results, &wg, caloriesPerMeal)
}
// Use a separate Goroutine to close the results channel when all Goroutines are done
go func() {
// Wait for all Goroutines to finish
wg.Wait()
close(results)
}()
var allRecipes []Recipe
// Receive and process recipes
for recipes := range results {
allRecipes = append(allRecipes, recipes...)
}
var responseRecipe []ResponseRecipe
for _, v := range allRecipes {
var r ResponseRecipe
r.Uri = v.Uri
r.Images = v.Images
r.Image = v.Image
r.Source = v.Source
r.Url = v.Url
r.ShareAs = v.ShareAs
r.Yield = v.Yield
r.DietLabels = v.DietLabels
r.HealthLabels = v.HealthLabels
r.Cautions = v.Cautions
r.IngredientLines = v.IngredientLines
r.GlycemicIndex = v.GlycemicIndex
r.TotalCO2Emissions = v.TotalCO2Emissions
r.Co2EmissionsClass = v.Co2EmissionsClass
r.TotalWeight = v.TotalWeight
r.Label = v.Label
r.Calories = v.Calories
r.MealType = v.MealType
var wgi sync.WaitGroup
ingredients := make(chan src.Food)
for _, value := range v.Ingredients {
wgi.Add(1)
go searchProduct(value.Food, &wgi, ingredients)
}
go func() {
// Wait for all Goroutines to finish
wgi.Wait()
close(ingredients)
}()
var foodIngredients []src.Food
// Receive and process recipes
for recipes := range ingredients {
foodIngredients = append(foodIngredients, recipes)
}
r.Ingredients = foodIngredients
responseRecipe = append(responseRecipe, r)
}
// Sample data
recipes := []ResponseRecipe{
{MealType: []string{"breakfast"}},
{MealType: []string{"lunch"}},
}
// Define a custom sorting function
sortByMealType := func(i, j int) bool {
return recipes[i].MealType[0] < recipes[j].MealType[0]
}
// Sort the slice based on the custom sorting function
sort.Slice(recipes, sortByMealType)
ctx.JSON(http.StatusOK, gin.H{"recipes": responseRecipe})
}
func main() {
r := gin.Default()
r.GET("api/v1/recipes/:calories", Recipes)
r.POST("api/v1/nutrition-calculator", src.CalculateCaloriesGet)
r.Run(":8088")
}