From 83c88e87bed30c6c1436823d7e814ae8ef766f85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leandro=20Ant=C3=B4nio=20Farias=20Machado?= Date: Thu, 20 Apr 2023 11:34:48 -0300 Subject: [PATCH] feat: api structure --- .../services/controller/internal/api/api.go | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 backend/services/controller/internal/api/api.go diff --git a/backend/services/controller/internal/api/api.go b/backend/services/controller/internal/api/api.go new file mode 100644 index 0000000..28969b4 --- /dev/null +++ b/backend/services/controller/internal/api/api.go @@ -0,0 +1,63 @@ +package api + +import ( + "encoding/json" + "github.com/gorilla/mux" + "github.com/leandrofars/oktopus/internal/db" + "log" + "net/http" + "time" +) + +type Api struct { + Port string + Db db.Database +} + +func NewApi(port string, db db.Database) Api { + return Api{ + Port: port, + Db: db, + } +} + +func StartApi(a Api) { + r := mux.NewRouter() + + r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + return + }) + r.HandleFunc("/devices", a.retrieveDevices) + //r.HandleFunc("/devices/{sn}", a.devicesMessaging) + + srv := &http.Server{ + Addr: "0.0.0.0:" + a.Port, + // Good practice to set timeouts to avoid Slowloris attacks. + WriteTimeout: time.Second * 15, + ReadTimeout: time.Second * 15, + IdleTimeout: time.Second * 60, + Handler: r, // Pass our instance of gorilla/mux in. + } + + // Run our server in a goroutine so that it doesn't block. + go func() { + if err := srv.ListenAndServe(); err != nil { + log.Println(err) + } + }() +} + +func (a *Api) retrieveDevices(w http.ResponseWriter, r *http.Request) { + devices, err := a.Db.RetrieveDevices() + if err != nil { + log.Println(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + err = json.NewEncoder(w).Encode(devices) + if err != nil { + log.Println(err) + } + + return +}