codec.go (1837B)
1 // This file is part of taler-cashless2ecash. 2 // Copyright (C) 2024 Joel Häberli 3 // 4 // taler-cashless2ecash is free software: you can redistribute it and/or modify it 5 // under the terms of the GNU Affero General Public License as published 6 // by the Free Software Foundation, either version 3 of the License, 7 // or (at your option) any later version. 8 // 9 // taler-cashless2ecash is distributed in the hope that it will be useful, but 10 // WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 // Affero General Public License for more details. 13 // 14 // You should have received a copy of the GNU Affero General Public License 15 // along with this program. If not, see <http://www.gnu.org/licenses/>. 16 // 17 // SPDX-License-Identifier: AGPL3.0-or-later 18 19 package internal_utils 20 21 import ( 22 "bytes" 23 "encoding/json" 24 "io" 25 ) 26 27 type Codec[T any] interface { 28 HttpApplicationContentHeader() string 29 Encode(*T) (io.Reader, error) 30 EncodeToBytes(body *T) ([]byte, error) 31 Decode(io.Reader) (*T, error) 32 } 33 34 type JsonCodec[T any] struct { 35 Codec[T] 36 } 37 38 func NewJsonCodec[T any]() Codec[T] { 39 40 return new(JsonCodec[T]) 41 } 42 43 func (*JsonCodec[T]) HttpApplicationContentHeader() string { 44 return "application/json" 45 } 46 47 func (*JsonCodec[T]) Encode(body *T) (io.Reader, error) { 48 49 encodedBytes, err := json.Marshal(body) 50 if err != nil { 51 return nil, err 52 } 53 54 return bytes.NewReader(encodedBytes), err 55 } 56 57 func (c *JsonCodec[T]) EncodeToBytes(body *T) ([]byte, error) { 58 59 reader, err := c.Encode(body) 60 if err != nil { 61 return make([]byte, 0), err 62 } 63 buf, err := io.ReadAll(reader) 64 if err != nil { 65 return make([]byte, 0), err 66 } 67 return buf, nil 68 } 69 70 func (*JsonCodec[T]) Decode(reader io.Reader) (*T, error) { 71 72 body := new(T) 73 err := json.NewDecoder(reader).Decode(body) 74 return body, err 75 }