Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
64 changes: 64 additions & 0 deletions .idea/workspace.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

33 changes: 0 additions & 33 deletions README.md

This file was deleted.

53 changes: 53 additions & 0 deletions application/app.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package application

import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
"net/http"
"time"
)

type App struct {
router http.Handler
rbd *redis.Client
}

func New() *App {
app := &App{rbd: redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0})}
app.loadRoutes()
return app
}

func (a *App) Start(ctx context.Context) error {
server := &http.Server{
Addr: ":3000",
Handler: a.router,
}
err := a.rbd.Ping(ctx).Err()
if err != nil {
return fmt.Errorf("Fail to connect redis: %w", err)
}

fmt.Println("Starting server")
ch := make(chan error, 1)
go func() {
err = server.ListenAndServe()
if err != nil {
ch <- fmt.Errorf("Failed to start server: %w", err)
}
close(ch)
}()

select {
case err = <-ch:
return err
case <-ctx.Done():
timeout, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
return server.Shutdown(timeout)
}
}
44 changes: 44 additions & 0 deletions application/routes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package application

import (
"assignment/handler"
"assignment/repository"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"net/http"
)

func (a *App) loadRoutes() {
router := chi.NewRouter()
router.Use(middleware.Logger)

router.Get("/", func(w http.ResponseWriter, request *http.Request) {
w.WriteHeader(http.StatusOK)
})

router.Route("/users", a.loadUserRoutes)
router.Route("/pings", a.loadPingRoutes)
a.router = router
}

func (a *App) loadPingRoutes(route chi.Router) {
pingHandler := &handler.Ping{
Repo: repository.RedisRepo{
Client: a.rbd,
}}
route.Post("/", pingHandler.PingEndPoint)
route.Get("/top_ten", pingHandler.GetTopTenCount)
route.Get("/{username}", pingHandler.GetPingCount)
}

func (a *App) loadUserRoutes(route chi.Router) {
userHandler := &handler.User{
Repo: repository.RedisRepo{
Client: a.rbd,
}}

route.Post("/", userHandler.SignIn)
route.Get("/", userHandler.List)
route.Get("/user/{username}", userHandler.GetUserById)
route.Get("/session/{session}", userHandler.LoginBySession)
}
16 changes: 16 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
module assignment

go 1.21

require (
github.com/bsm/redislock v0.9.4
github.com/go-chi/chi/v5 v5.0.10
github.com/go-redis/redis_rate/v10 v10.0.1
github.com/google/uuid v1.4.0
github.com/redis/go-redis/v9 v9.3.0
)

require (
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
)
26 changes: 26 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/bsm/redislock v0.9.4 h1:X/Wse1DPpiQgHbVYRE9zv6m070UcKoOGekgvpNhiSvw=
github.com/bsm/redislock v0.9.4/go.mod h1:Epf7AJLiSFwLCiZcfi6pWFO/8eAYrYpQXFxEDPoDeAk=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/go-chi/chi/v5 v5.0.10 h1:rLz5avzKpjqxrYwXNfmjkrYYXOyLJd37pz53UFHC6vk=
github.com/go-chi/chi/v5 v5.0.10/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-redis/redis_rate/v10 v10.0.1 h1:calPxi7tVlxojKunJwQ72kwfozdy25RjA0bCj1h0MUo=
github.com/go-redis/redis_rate/v10 v10.0.1/go.mod h1:EMiuO9+cjRkR7UvdvwMO7vbgqJkltQHtwbdIQvaBKIU=
github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4=
github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.3.0 h1:RiVDjmig62jIWp7Kk4XVLs0hzV6pI3PyTnnL0cnn0u0=
github.com/redis/go-redis/v9 v9.3.0/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
103 changes: 103 additions & 0 deletions handler/ping.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package handler

import (
"assignment/model"
"assignment/repository"
"encoding/json"
"errors"
"fmt"
"github.com/go-chi/chi/v5"
"net/http"
)

type Ping struct {
Repo repository.RedisRepo
}

func (p *Ping) PingEndPoint(
w http.ResponseWriter,
r *http.Request,
) {
err := p.Repo.PingEntryPoint(r.Context())
if errors.Is(err, repository.CannotPingMultiply) {
fmt.Errorf("Cannot ping mutiply times: %w", err)
w.WriteHeader(http.StatusAlreadyReported)
return
}

var username model.User
if err := json.NewDecoder(r.Body).Decode(&username); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}

err = p.Repo.RateLimit(r.Context(), username.Username)
if errors.Is(err, repository.RedisError) {
fmt.Println("redis error:", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if errors.Is(err, repository.TooManyRequest) {
fmt.Println("Too many request:", err)
w.WriteHeader(http.StatusTooManyRequests)
return
}

err = p.Repo.CountPing(r.Context(), username.Username)
if err != nil {
fmt.Println("failed to count:", err)
w.WriteHeader(http.StatusInternalServerError)
return
}

data, err := json.Marshal("Ping successfully!")
if err != nil {
fmt.Println("failed to marshal:", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(data)
}

func (p *Ping) GetTopTenCount(
w http.ResponseWriter,
r *http.Request,
) {
topTen, err := p.Repo.GetTopCount(r.Context())
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
data, err := json.Marshal(topTen)
if err != nil {
fmt.Println("failed to marshal:", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(data)
}

func (p *Ping) GetPingCount(
w http.ResponseWriter,
r *http.Request,
) {
username := chi.URLParam(r, "username")
count, err := p.Repo.GetPingCount(r.Context(), username)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if len(count) != 1 {
w.WriteHeader(http.StatusNotFound)
return
}

data, err := json.Marshal(count)
if err != nil {
fmt.Println("failed to marshal:", err)
w.WriteHeader(http.StatusInternalServerError)
return
}

w.Write(data)
}
Loading