From 28e6e3798b269709a9f2c7fe2e638225ef02ba1f Mon Sep 17 00:00:00 2001 From: Carlo Field Date: Thu, 9 Apr 2020 09:43:55 +0200 Subject: [PATCH] add get and update calls for characters --- internal/server/character.go | 44 +++++++++++++++++++++++++++++++++++- internal/server/server.go | 6 ++--- 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/internal/server/character.go b/internal/server/character.go index fb1f5d2..3a37de8 100644 --- a/internal/server/character.go +++ b/internal/server/character.go @@ -6,7 +6,9 @@ import ( "regexp" "strconv" + "github.com/cfi2017/bl3-save/internal/shared" "github.com/cfi2017/bl3-save/pkg/character" + "github.com/cfi2017/bl3-save/pkg/pb" "github.com/gin-gonic/gin" ) @@ -14,7 +16,7 @@ var ( charPattern = regexp.MustCompile("(\\d+)\\.sav") ) -func ListCharacters(c *gin.Context) { +func listCharacters(c *gin.Context) { files, err := ioutil.ReadDir(pwd) if err != nil { c.AbortWithStatus(500) @@ -35,6 +37,46 @@ func ListCharacters(c *gin.Context) { } +func getCharacter(c *gin.Context) { + id := c.Param("id") + + f, err := os.Open(pwd + "/" + id + ".sav") + if err != nil { + c.AbortWithStatus(500) + return + } + defer f.Close() + s, char := character.Deserialize(f) + c.JSON(200, struct { + Save shared.SavFile `json:"save"` + Character pb.Character `json:"character"` + }{Save: s, Character: char}) + +} + +func updateCharacter(c *gin.Context) { + id := c.Param("id") + + var d struct { + Save shared.SavFile `json:"save"` + Character pb.Character `json:"character"` + } + err := c.BindJSON(&d) + if err != nil { + c.AbortWithStatus(500) + return + } + f, err := os.Create(pwd + "/" + id + ".sav") + if err != nil { + c.AbortWithStatus(500) + return + } + defer f.Close() + character.Serialize(f, d.Save, d.Character) + c.Status(204) + return +} + type CharInfo struct { ID int `json:"id"` Name string `json:"name"` diff --git a/internal/server/server.go b/internal/server/server.go index f59f889..99aa4f8 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -53,9 +53,9 @@ func Start() error { r.GET("/profile", getProfile) r.POST("/profile", updateProfile) - r.GET("/characters", ListCharacters) - r.GET("/characters/:id") - r.POST("/characters/:id") + r.GET("/characters", listCharacters) + r.GET("/characters/:id", getCharacter) + r.POST("/characters/:id", updateCharacter) return r.Run(":5050") }