-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
54 lines (46 loc) · 1.09 KB
/
main.go
File metadata and controls
54 lines (46 loc) · 1.09 KB
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
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"time"
"github.com/25b3nk/learnCache/cache"
"github.com/gofiber/fiber/v2"
)
// Response structure from jsonplaceholder
type Todo struct {
UserId int `json:"userId"`
Id int `json:"id"`
Title string `json:"title"`
Completed bool `json:"completed"`
}
const url = "https://jsonplaceholder.typicode.com/todos/"
func main() {
app := fiber.New()
cache.Cache.SetTTL(time.Duration(10 * time.Second))
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Server running")
})
app.Get("/:id", cache.VerifyCache, func(c *fiber.Ctx) error {
id := c.Params("id")
res, err := http.Get(url + id)
if err != nil {
return err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
todo := Todo{}
// Unmarshal the json into the structure
parseErr := json.Unmarshal(body, &todo)
if parseErr != nil {
return parseErr
}
cache.Cache.Set(id, todo)
return c.JSON(fiber.Map{"data": todo})
})
// Server hosted on localhost:3000
app.Listen(":3000")
}