feat: http router, command api
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/iliadenisov/galaxy/internal/game"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/iliadenisov/galaxy/internal/controller"
|
||||
"github.com/iliadenisov/galaxy/internal/model/rest"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrCommandNotProcessed = errors.New("command was not processed by executor")
|
||||
)
|
||||
|
||||
func CommandHandler(c *gin.Context, executor Executor) {
|
||||
var cmd rest.Command
|
||||
if err := c.ShouldBindJSON(&cmd); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
err := executor(cmd)
|
||||
switch {
|
||||
case err == nil:
|
||||
c.Status(http.StatusOK)
|
||||
case errors.Is(err, ErrCommandNotProcessed):
|
||||
c.Status(http.StatusInternalServerError)
|
||||
default:
|
||||
// TODO: separate bad value errors and game state errors
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
}
|
||||
}
|
||||
|
||||
func Execute(cmd rest.Command) error {
|
||||
p := func(p *controller.Param) {
|
||||
// TODO: initialize base controller settings
|
||||
p.StoragePath = ""
|
||||
}
|
||||
switch {
|
||||
case cmd.DeclareWar != nil:
|
||||
return game.DeclareWar(p, cmd.Race, cmd.DeclareWar.Opponent)
|
||||
case cmd.DeclarePeace != nil:
|
||||
return game.DeclarePeace(p, cmd.Race, cmd.DeclareWar.Opponent)
|
||||
default:
|
||||
return ErrCommandNotProcessed
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user