92 lines
2.3 KiB
Go
92 lines
2.3 KiB
Go
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)) }
|