Skip to content

Commit

Permalink
Improve error logging and response to the user
Browse files Browse the repository at this point in the history
- The write time out of the http server was increased for proper
response in case of duplicate
- Spit the errors to confict and server error
- Add logging
- Update function comments
  • Loading branch information
kostas-kou committed Oct 14, 2024
1 parent 5fc3703 commit 08898c8
Showing 1 changed file with 32 additions and 6 deletions.
38 changes: 32 additions & 6 deletions sda/cmd/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func setup(config *config.Config) *http.Server {
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
ReadHeaderTimeout: 20 * time.Second,
ReadTimeout: 5 * time.Minute,
WriteTimeout: 20 * time.Second,
WriteTimeout: 2 * time.Minute,
}

return srv
Expand Down Expand Up @@ -393,7 +393,12 @@ func listUserFiles(c *gin.Context) {
c.JSON(200, files)
}

// addHashedKey function adds a hashed public key and its description to the database
// addHashedKey handles the addition of a hashed key to the database.
// It expects a JSON payload containing the key hash and its description.
// If the JSON payload is invalid, it responds with a 400 Bad Request status.
// If there is no row update in the database, it responds with a 409 Conflict status
// If the database insertion fails, it responds with a 500 Internal Server Error status.
// On success, it responds with a 200 OK status.
func addHashedKey(c *gin.Context) {
var keyhash schema.KeyhashInsertion
if err := c.BindJSON(&keyhash); err != nil {
Expand All @@ -405,14 +410,35 @@ func addHashedKey(c *gin.Context) {
},
)

log.Errorf("Invalid JSON payload: %v", err)

return
}

err = Conf.API.DB.AddKeyHash(keyhash.Hash, keyhash.Description)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, err.Error())
return
}
if err != nil {
if strings.Contains(err.Error(), "key hash already exists") {
c.AbortWithStatusJSON(
http.StatusConflict,
gin.H{
"error": err.Error(),
"status": http.StatusConflict,
},
)
log.Error("Key hash already exists")
} else {
c.AbortWithStatusJSON(
http.StatusInternalServerError,
gin.H{
"error": err.Error(),
"status": http.StatusInternalServerError,
},
)
log.Errorf("Database insertion failed: %v", err)
}

return
}

c.Status(http.StatusOK)
}

0 comments on commit 08898c8

Please sign in to comment.