feat: add getting visitor counter

This commit is contained in:
axolotlmaid 2024-09-25 17:55:40 +01:00
parent 0f2d805df2
commit bd31a363df
4 changed files with 58 additions and 0 deletions

View file

@ -0,0 +1,18 @@
package handler
import (
"backend/internal/service"
"encoding/json"
"net/http"
)
func HandleGetVisitorCounter(w http.ResponseWriter, r *http.Request) {
data := service.GetVisitorCounter()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(data)
}
func HandlePatchVisitorCounter(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world"))
}

View file

@ -0,0 +1,5 @@
package model
type VisitorCounter struct {
Counter uint32 `json:"counter"`
}

View file

@ -8,6 +8,8 @@ import (
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"backend/internal/handler"
)
func NewRouter() {
@ -24,6 +26,9 @@ func NewRouter() {
http.Redirect(w, r, "https://axolotlmaid.com", http.StatusPermanentRedirect)
})
r.Get("/visitor-counter", handler.HandleGetVisitorCounter)
r.Patch("/visitor-counter", handler.HandlePatchVisitorCounter)
slog.Info("Starting server", slog.Any("port", os.Getenv("PORT")))
http.ListenAndServe(":"+os.Getenv("PORT"), r)
}

View file

@ -0,0 +1,30 @@
package service
import (
"encoding/json"
"io"
"log/slog"
"os"
"path/filepath"
"backend/internal/model"
)
func GetVisitorCounter() model.VisitorCounter {
path := filepath.Join(".", "data", "visitor.json")
jsonFile, err := os.Open(path)
if err != nil {
slog.Warn("File not found!", slog.Any("file", path))
return model.VisitorCounter{}
}
bytes, _ := io.ReadAll(jsonFile)
var data model.VisitorCounter
err = json.Unmarshal(bytes, &data)
if err != nil {
slog.Error("Error unmarshalling JSON", slog.Any("error", err), slog.Any("file", path))
}
return data
}