From 5a1e5f6f7fc31647214fa698060fff61a1236ec5 Mon Sep 17 00:00:00 2001 From: Sander Schobers Date: Fri, 15 May 2020 11:33:33 +0200 Subject: [PATCH] Added image & JSON encoding/decoding facilities. --- io.go | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 io.go diff --git a/io.go b/io.go new file mode 100644 index 0000000..8a99469 --- /dev/null +++ b/io.go @@ -0,0 +1,91 @@ +package zntg + +import ( + "encoding/json" + "image" + _ "image/gif" // decoding of GIF + _ "image/jpeg" // decoding of JPEG + "image/png" + "io" + "os" +) + +// CreateJSONDecoder create a new a generic JSON decoder for the specified value. +func CreateJSONDecoder(value interface{}) DecoderFn { + return func(r io.Reader) (interface{}, error) { + decoder := json.NewDecoder(r) + return value, decoder.Decode(value) + } +} + +// DecoderFn describes a generic decoder. +type DecoderFn func(io.Reader) (interface{}, error) + +// DecodeFile is a generic decode method to decode content from disk. +func DecodeFile(path string, decoder func(io.Reader) (interface{}, error)) (interface{}, error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + return decoder(f) +} + +// DecodeImage tries to decode a file to an image. +func DecodeImage(path string) (image.Image, error) { + value, err := DecodeFile(path, ImageDecoder) + if err != nil { + return nil, err + } + return value.(image.Image), nil +} + +// DecodeJSON tries to decode a file to specifed value. +func DecodeJSON(path string, value interface{}) error { + _, err := DecodeFile(path, CreateJSONDecoder(value)) + return err +} + +// EncoderFn describes a generic encoder. +type EncoderFn func(io.Writer, interface{}) error + +// EncodeFile is a generic encode method to encode content to disk. +func EncodeFile(path string, value interface{}, encoder EncoderFn) error { + dst, err := os.Create(path) + if err != nil { + return err + } + defer dst.Close() + return encoder(dst, value) +} + +// EncodeJSON encodes a JSON struct to a file. +func EncodeJSON(path string, value interface{}) error { + return EncodeFile(path, value, JSONEncoder) +} + +// EncodePNG encodes an image to a file. +func EncodePNG(path string, im image.Image) error { + return EncodeFile(path, im, PNGEncoder) +} + +var _ DecoderFn = ImageDecoder + +// ImageDecoder is a generic image decoder. +func ImageDecoder(r io.Reader) (interface{}, error) { + im, _, err := image.Decode(r) + return im, err +} + +var _ EncoderFn = JSONEncoder + +// JSONEncoder is a generic JSON encoder. +func JSONEncoder(w io.Writer, value interface{}) error { + encoder := json.NewEncoder(w) + return encoder.Encode(value) +} + +var _ EncoderFn = PNGEncoder + +// PNGEncoder is a generic PNG encoder. +func PNGEncoder(w io.Writer, value interface{}) error { return png.Encode(w, value.(image.Image)) }