json, gob 둘다 지원

This commit is contained in:
2023-09-11 12:45:15 +09:00
parent 23231dc6d7
commit 1af5d72819
3 changed files with 44 additions and 22 deletions

View File

@ -430,17 +430,44 @@ func ReadStringFormValue(r url.Values, key string) (string, bool) {
return strval, len(strval) > 0
}
func DecodeGob[T any](r io.Reader, out *T) error {
dec := gob.NewDecoder(r)
return dec.Decode(out)
type encoder interface {
Encode(any) error
}
func ReadJsonDocumentFromBody[T any](r io.Reader, out *T) error {
bt, err := io.ReadAll(r)
if err != nil {
return err
type nilEncoder struct{}
func (ne *nilEncoder) Encode(any) error { return nil }
type decoder interface {
Decode(any) error
}
type nilDecoder struct{}
func (nd *nilDecoder) Decode(any) error { return nil }
func MakeDecoder(r *http.Request) decoder {
ct := r.Header.Get("Content-Type")
if ct == "application/gob" {
return gob.NewDecoder(r.Body)
} else if ct == "application/json" {
return json.NewDecoder(r.Body)
}
return json.Unmarshal(bt, out)
logger.Error("Content-Type is not supported :", ct)
return &nilDecoder{}
}
func MakeEncoder(w http.ResponseWriter, r *http.Request) encoder {
ct := r.Header.Get("Content-Type")
if ct == "application/gob" {
return gob.NewEncoder(w)
} else if ct == "application/json" {
return json.NewEncoder(w)
}
logger.Error("Content-Type is not supported :", ct)
return &nilEncoder{}
}
func DotStringToTimestamp(tv string) primitive.Timestamp {