refactor everything again
All checks were successful
Build and Publish / BuildAndDeploy (push) Successful in 1m51s

This commit is contained in:
matst80
2024-11-10 20:10:47 +01:00
parent 7a4d9b1540
commit 8f0e062817
7 changed files with 125 additions and 145 deletions

58
pool-server.go Normal file
View File

@@ -0,0 +1,58 @@
package main
import (
"net/http"
messages "git.tornberg.me/go-cart-actor/proto"
)
type PoolServer struct {
pod_name string
pool GrainPool
}
func NewPoolServer(pool GrainPool, pod_name string) *PoolServer {
return &PoolServer{
pod_name: pod_name,
pool: pool,
}
}
func (s *PoolServer) HandleGet(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
data, err := s.pool.Get(ToCartId(id))
if err != nil {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(err.Error()))
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Pod-Name", s.pod_name)
w.WriteHeader(http.StatusOK)
w.Write(data)
}
func (s *PoolServer) HandleAddSku(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
sku := r.PathValue("sku")
data, err := s.pool.Process(ToCartId(id), Message{
Type: AddRequestType,
Content: &messages.AddRequest{Sku: sku},
})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Pod-Name", s.pod_name)
w.WriteHeader(http.StatusOK)
w.Write(data)
}
func (s *PoolServer) Serve() *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("GET /{id}", s.HandleGet)
mux.HandleFunc("GET /{id}/add/{sku}", s.HandleAddSku)
return mux
}