From 96b35f5022d2b29b6dd37771949f44377485d82d Mon Sep 17 00:00:00 2001 From: Cara Salter Date: Wed, 25 Oct 2023 13:48:26 -0400 Subject: [PATCH] fix: Enable scanning of JSON types from SQL See gist here: https://gist.github.com/rrafal/09534862e05cd98e4eb9b17dd5fcc1fc --- internal/models/models.go | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/internal/models/models.go b/internal/models/models.go index 58daba8..edc9099 100644 --- a/internal/models/models.go +++ b/internal/models/models.go @@ -1,5 +1,12 @@ package models +import ( + "database/sql/driver" + "encoding/json" + "errors" + "fmt" +) + type User struct { Username string `json:"username" validate:"required"` Password string `json:"password" validate:"required"` @@ -32,8 +39,8 @@ type Stead struct { Id int Username string Password string - Inventory map[string]interface{} - Ephemeral_statuses map[string]interface{} + Inventory JsonValue + Ephemeral_statuses JsonValue } type PlantKind string @@ -45,6 +52,24 @@ const ( HVV PlantKind = "hvv" ) +type JsonValue map[string]interface{} + +func (jval *JsonValue) Scan(val interface{}) error { + switch v := val.(type) { + case []byte: + json.Unmarshal(v, &jval) + return nil + case string: + json.Unmarshal([]byte(v), &jval) + return nil + default: + return errors.New(fmt.Sprintf("Unsupported type: %T", v)) + } +} +func (jval *JsonValue) Value() (driver.Value, error) { + return json.Marshal(jval) +} + //func (s *PlantKind) Scan(value interface{}) error { // asBytes, ok := value.([]byte) // if !ok {