Any good examples of custom type scanners/encoders that carry state? #2121
-
Hey folks, I just spent a few hours trying to wrap my head around getting a custom type registered in pgx which should encrypt/decrypt its values transparently, but without much success. Are there any good examples of values that have scanners/encoders that carry state anywhere? Or good documentation on how to write custom ones? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
It's pretty easy to define a new type that transforms its values. For example, if you are strictly encrypting strings, you could implement
But that's the problem. Your new type could reference a single global key, but it sounds like you need multiple keys. Here's one approach, you would need some sort of object that had the key that would wrap the underlying value. Something like: type TextCryptor {
// ...
}
func (c *TextCryptor) Scanner(target string) TextScanner {
// return a TextScanner that decrypts the cyphertext and stores the plaintext in target
}
func (c *TextCryptor) Value(value string) TextValuer {
// return a TextValuer that encrypts the plaintext and returns the cyphertext
}
cryptor := TextCryptor{key: "..."}
var ssn string
conn.Query(...).Scan(cryptor.Scanner(&ssn)) I don't know any simpler way to do it. |
Beta Was this translation helpful? Give feedback.
-
I think this might just work. I went down a rabbit hole of custom type registrations and the like. Thanks for the prompt response! UPDATE This worked like a charm! Thank you again for your help ❤️ |
Beta Was this translation helpful? Give feedback.
It's pretty easy to define a new type that transforms its values. For example, if you are strictly encrypting strings, you could implement
TextScanner
andTextValuer
.But that's the problem. Your new type could reference a single global key, but it sounds like you need multiple keys.
Here's one approach, you would need some sort of object that had the key that would wrap the underlying value. Something like: