Files
zeekayandHanzo Dev 4be00f32ab Go 1.27.1, and the code it can say more simply
Modules declare go 1.27.1 and the build images follow. go fix applied the
modernizers: any, reflect.TypeFor, the atomic types, WaitGroup.Go, the
reflect field iterators, CutPrefix, SplitSeq, strings.Builder and range over
int. omitzero is not applied, since it changes what the JSON says.

Co-authored-by: Hanzo Dev <[email protected]>
2026-09-16 19:46:12 -07:00

85 lines
1.9 KiB
Go

// Package json provides JSON encoding/decoding utilities.
package json
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"strings"
)
// isDevelopment checks if we're in development mode.
var isDevelopment = func() bool {
env := os.Getenv("HANZO_ENV")
if env == "" {
env = os.Getenv("GAE_ENV")
}
return env == "" || strings.ToLower(env) == "development" || strings.ToLower(env) == "dev"
}()
// Encode marshals a value to a JSON string.
func Encode(value any) string {
return string(EncodeBytes(value))
}
// EncodeBytes marshals a value to JSON bytes.
func EncodeBytes(value any) []byte {
var b []byte
var err error
if isDevelopment {
b, err = json.MarshalIndent(value, "", " ")
} else {
b, err = json.Marshal(value)
}
if err != nil {
fmt.Printf("json encode error: %v\n", err)
}
return b
}
// EncodeIndentBytes marshals with custom indentation.
func EncodeIndentBytes(value any, prefix, indent string) []byte {
b, err := json.MarshalIndent(value, prefix, indent)
if err != nil {
fmt.Printf("json encode error: %v\n", err)
}
return b
}
// EncodeRaw marshals to json.RawMessage.
func EncodeRaw(value any) json.RawMessage {
return json.RawMessage(EncodeBytes(value))
}
// EncodeBuffer marshals to a bytes.Buffer.
func EncodeBuffer(value any) *bytes.Buffer {
return bytes.NewBuffer(EncodeBytes(value))
}
// Decode reads and unmarshals from an io.ReadCloser.
func Decode(body io.ReadCloser, dst any) error {
data, err := io.ReadAll(body)
body.Close()
if err != nil {
return err
}
return json.Unmarshal(data, dst)
}
// DecodeBytes unmarshals from bytes.
func DecodeBytes(data []byte, dst any) error {
return json.Unmarshal(data, dst)
}
// DecodeBuffer unmarshals from a buffer.
func DecodeBuffer(buf *bytes.Buffer, dst any) error {
return json.Unmarshal(buf.Bytes(), dst)
}
// Unmarshal is an alias for json.Unmarshal.
var Unmarshal = json.Unmarshal