Help us shape the future of Go! Take the 2026 Go Developer Survey

guard

package module
v0.0.0-...-a5bb8cf Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 31, 2024 License: MIT Imports: 1 Imported by: 0

README

guard

Dead simple json marshal guard for potential data type mismatch (eg. marshal array into struct, string into object).

Usage

See Doc

package main

import (
	"encoding/json"
	"fmt"
	"github.com/Sora233/guard"
)

func main() {
	var response struct {
		Code int    `json:"code"`
		Msg  string `json:"msg"`
		Data guard.Guard[struct {
			Content string `json:"content"`
		}] `json:"data"`
	}
	var body = `{"code":10000, "msg":"xx error", "data": "wrong format"}`

	err := json.Unmarshal([]byte(body), &response)
	if err != nil {
		fmt.Println("can not unmarshal body", err.Error())
		return
	}
	if response.Data.IsSuccess() {
		fmt.Println("content is", response.Data.Get().Content)
	} else {
		fmt.Println("can not get content because of wrong body data", string(response.Data.GetRaw()))
	}
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Guard

type Guard[T any] struct {
	// contains filtered or unexported fields
}

Guard is a dead simple json marshal guard

Example
package main

import (
	"encoding/json"
	"fmt"
	"github.com/Sora233/guard"
)

func main() {
	var response struct {
		Code int    `json:"code"`
		Msg  string `json:"msg"`
		Data guard.Guard[struct {
			Content string `json:"content"`
		}] `json:"data"`
	}
	var body = `{"code":10000, "msg":"xx error", "data": "wrong format"}`

	err := json.Unmarshal([]byte(body), &response)
	if err != nil {
		fmt.Println("can not unmarshal body", err.Error())
		return
	}
	if response.Data.IsSuccess() {
		fmt.Println("content is", response.Data.Get().Content)
	} else {
		fmt.Println("can not get content because of wrong body data", string(response.Data.GetRaw()))
	}
}

func (*Guard[T]) Fail

func (g *Guard[T]) Fail(raw []byte)

func (*Guard[T]) Get

func (g *Guard[T]) Get() T

Get gets the data

func (*Guard[T]) GetPtr

func (g *Guard[T]) GetPtr() *T

GetPtr gets the pointer of data

func (*Guard[T]) GetRaw

func (g *Guard[T]) GetRaw() []byte

GetRaw gets the original marshal bytes

func (*Guard[T]) IsSuccess

func (g *Guard[T]) IsSuccess() bool

IsSuccess indicates if the unmarshal is success

func (*Guard[T]) Success

func (g *Guard[T]) Success(data T)

func (*Guard[T]) UnmarshalJSON

func (g *Guard[T]) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the json unmarshal interface

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL