strval

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2025 License: MIT Imports: 7 Imported by: 0

README

go-strval

Go 库提供了增强的基本类型(Bool、Int、Float),支持从字符串形式的 JSON/YAML 反序列化到相应的基本类型。

功能特点

  • Bool 类型:支持从字符串形式(如 "true", "false", "yes", "no", "1", "0")反序列化为 bool 值
  • Int 类型:支持从字符串形式反序列化为 int 值
  • Float 类型:支持从字符串形式反序列化为 float64 值
  • String 类型:支持从多种类型(字符串、数值、布尔值)转换为字符串
  • 优雅处理错误:当格式异常时,会将值设置为零值,并使用 slog 记录详细错误信息
  • 标准序列化:序列化为 JSON/YAML 时输出原始类型值,而不是字符串
  • 数据库支持:实现了 driver.Valuersql.Scanner 接口,支持与 GORM 等 ORM 框架配合使用

安装

go get github.com/geassgo/go-strval

使用示例

基本使用
package main

import (
	"encoding/json"
	"fmt"

	"github.com/geassgo/go-strval"
)

type Config struct {
	Enabled  strval.Bool   `json:"enabled"`
	MaxCount strval.Int    `json:"maxCount"`
	Timeout  strval.Float  `json:"timeout"`
}

func main() {
	// JSON 反序列化(字符串形式)
	jsonData := []byte(`{
		"enabled": "true",
		"maxCount": "100",
		"timeout": "3.5"
	}`)

	var config Config
	err := json.Unmarshal(jsonData, &config)
	if err != nil {
		panic(err)
	}

	// 直接使用转换后的基本类型值
	fmt.Printf("Enabled: %v\n", bool(config.Enabled))   // true
	fmt.Printf("MaxCount: %v\n", int(config.MaxCount))   // 100
	fmt.Printf("Timeout: %v\n", float64(config.Timeout)) // 3.5

	// JSON 序列化(输出原始类型)
	output, err := json.Marshal(config)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(output)) // {"enabled":true,"maxCount":100,"timeout":3.5}
}
YAML 支持
package main

import (
	"fmt"

	"github.com/geassgo/go-strval"
	"gopkg.in/yaml.v3"
)

type YAMLConfig struct {
	Enabled  strval.Bool   `yaml:"enabled"`
	MaxCount strval.Int    `yaml:"maxCount"`
	Timeout  strval.Float  `yaml:"timeout"`
}

func main() {
	// YAML 反序列化
	yamlData := []byte(`
enabled: "false"
maxCount: "200"
timeout: "5.25"
`)

	var config YAMLConfig
	err := yaml.Unmarshal(yamlData, &config)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Enabled: %v\n", bool(config.Enabled))   // false
	fmt.Printf("MaxCount: %v\n", int(config.MaxCount))   // 200
	fmt.Printf("Timeout: %v\n", float64(config.Timeout)) // 5.25
}
GORM 支持
package main

import (
	"fmt"

	"github.com/lengpucheng/go-strval"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

// 定义模型
type User struct {
	ID     uint   `gorm:"primaryKey"`
	Name   string `gorm:"size:255"`
	Active strval.Bool   `gorm:"column:active"`
	Age    strval.Int    `gorm:"column:age"`
	Score  strval.Float  `gorm:"column:score"`
	Status strval.String `gorm:"column:status"`
}

func main() {
	// 连接数据库
	db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
	if err != nil {
		panic("Failed to connect database")
	}

	// 自动迁移表结构
	db.AutoMigrate(&User{})

	// 创建记录
	user := User{
		Name:   "John Doe",
		Active: strval.Bool(true),
		Age:    strval.Int(30),
		Score:  strval.Float(95.5),
		Status: strval.String("active"),
	}
	db.Create(&user)

	// 查询记录
	var foundUser User
	db.First(&foundUser, user.ID)

	// 输出结果
	fmt.Printf("User: %+v\n", foundUser)
	fmt.Printf("Active: %v\n", bool(foundUser.Active))
	fmt.Printf("Age: %v\n", int(foundUser.Age))
	fmt.Printf("Score: %v\n", float64(foundUser.Score))
	fmt.Printf("Status: %v\n", string(foundUser.Status))
}

错误处理

当解析失败时,库会:

  1. 将值设置为对应类型的零值(false, 0, 0.0)
  2. 使用 slog 记录详细的错误信息,包括原始值和具体错误

例如,当解析无效的布尔值字符串时:

ERROR invalid Bool string value value=invalid error="cannot parse 'invalid' as bool"

测试

运行测试以验证功能:

go test -v ./...

类型转换

所有类型都可以直接转换为对应的基本类型:

var b strval.Bool = true
basicBool := bool(b)

var i strval.Int = 42
basicInt := int(i)

var f strval.Float = 3.14
basicFloat := float64(f)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bool

type Bool bool

Bool 增强的布尔类型,支持从字符串形式的JSON/YAML反序列化

func (Bool) GetValue

func (b Bool) GetValue() bool

GetValue 实现StringValuer[bool]接口,获取包装的原始布尔值 返回值:

  • bool: 原始的bool值

func (Bool) MarshalJSON

func (b Bool) MarshalJSON() ([]byte, error)

MarshalJSON 实现json.Marshaler接口,将Bool序列化为JSON布尔值 返回值:

  • []byte: 序列化后的JSON字节
  • error: 序列化过程中的错误

func (Bool) MarshalYAML

func (b Bool) MarshalYAML() (interface{}, error)

MarshalYAML 实现yaml.Marshaler接口,将Bool序列化为YAML布尔值 返回值:

  • interface{}: 序列化后的值
  • error: 序列化过程中的错误

func (*Bool) Scan

func (b *Bool) Scan(value interface{}) error

Scan 实现sql.Scanner接口,用于数据库读取操作 参数:

  • value: 从数据库读取的值

返回值:

  • error: 扫描过程中的错误

func (*Bool) UnmarshalJSON

func (b *Bool) UnmarshalJSON(data []byte) error

UnmarshalJSON 实现json.Unmarshaler接口,支持从JSON布尔值或字符串反序列化为Bool 参数:

  • data: JSON数据字节

返回值:

  • error: 反序列化过程中的错误

说明:

  • 支持直接解析JSON布尔值
  • 支持解析字符串形式的布尔值(如"true"、"false"、"yes"、"no"、"1"、"0")
  • 解析失败时返回false并记录错误日志

func (*Bool) UnmarshalYAML

func (b *Bool) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML 实现yaml.Unmarshaler接口,支持从YAML布尔值或字符串反序列化为Bool 参数:

  • node: YAML节点

返回值:

  • error: 反序列化过程中的错误

说明:

  • 支持直接解析YAML布尔值
  • 支持解析字符串形式的布尔值
  • 解析失败时返回false并记录错误日志

func (Bool) Value

func (b Bool) Value() (driver.Value, error)

Value 实现driver.Valuer接口,用于数据库写入操作 返回值:

  • driver.Value: 数据库可接受的值
  • error: 转换过程中的错误

type Float

type Float float64

Float 增强的浮点型,支持从字符串形式的JSON/YAML反序列化

func (Float) GetValue

func (f Float) GetValue() float64

GetValue 实现StringValuer[float64]接口,获取包装的原始浮点值 返回值:

  • float64: 原始的float64值

func (Float) MarshalJSON

func (f Float) MarshalJSON() ([]byte, error)

MarshalJSON 实现json.Marshaler接口,将Float序列化为JSON数值 返回值:

  • []byte: 序列化后的JSON字节
  • error: 序列化过程中的错误

func (Float) MarshalYAML

func (f Float) MarshalYAML() (interface{}, error)

MarshalYAML 实现yaml.Marshaler接口,将Float序列化为YAML数值 返回值:

  • interface{}: 序列化后的值
  • error: 序列化过程中的错误

func (*Float) Scan

func (f *Float) Scan(value interface{}) error

Scan 实现sql.Scanner接口,用于数据库读取操作 参数:

  • value: 从数据库读取的值

返回值:

  • error: 扫描过程中的错误

func (*Float) UnmarshalJSON

func (f *Float) UnmarshalJSON(data []byte) error

UnmarshalJSON 实现json.Unmarshaler接口,支持从JSON数值或字符串反序列化为Float 参数:

  • data: JSON数据字节

返回值:

  • error: 反序列化过程中的错误

说明:

  • 支持直接解析JSON数值
  • 支持解析字符串形式的浮点数值
  • 解析失败时返回0并记录错误日志

func (*Float) UnmarshalYAML

func (f *Float) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML 实现yaml.Unmarshaler接口,支持从YAML数值或字符串反序列化为Float 参数:

  • node: YAML节点

返回值:

  • error: 反序列化过程中的错误

说明:

  • 支持直接解析YAML数值
  • 支持解析字符串形式的浮点数值
  • 解析失败时返回0并记录错误日志

func (Float) Value

func (f Float) Value() (driver.Value, error)

Value 实现driver.Valuer接口,用于数据库写入操作 返回值:

  • driver.Value: 数据库可接受的值
  • error: 转换过程中的错误

type Int

type Int int

Int 增强的整型,支持从字符串形式的JSON/YAML反序列化

func (Int) GetValue

func (i Int) GetValue() int

GetValue 实现StringValuer[int]接口,获取包装的原始整数值 返回值:

  • int: 原始的int值

func (Int) MarshalJSON

func (i Int) MarshalJSON() ([]byte, error)

MarshalJSON 实现json.Marshaler接口,将Int序列化为JSON数值 返回值:

  • []byte: 序列化后的JSON字节
  • error: 序列化过程中的错误

func (Int) MarshalYAML

func (i Int) MarshalYAML() (interface{}, error)

MarshalYAML 实现yaml.Marshaler接口,将Int序列化为YAML数值 返回值:

  • interface{}: 序列化后的值
  • error: 序列化过程中的错误

func (*Int) Scan

func (i *Int) Scan(value interface{}) error

Scan 实现sql.Scanner接口,用于数据库读取操作 参数:

  • value: 从数据库读取的值

返回值:

  • error: 扫描过程中的错误

func (*Int) UnmarshalJSON

func (i *Int) UnmarshalJSON(data []byte) error

UnmarshalJSON 实现json.Unmarshaler接口,支持从JSON数值或字符串反序列化为Int 参数:

  • data: JSON数据字节

返回值:

  • error: 反序列化过程中的错误

说明:

  • 支持直接解析JSON数值
  • 支持解析字符串形式的整数值
  • 解析失败时返回0并记录错误日志

func (*Int) UnmarshalYAML

func (i *Int) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML 实现yaml.Unmarshaler接口,支持从YAML数值或字符串反序列化为Int 参数:

  • node: YAML节点

返回值:

  • error: 反序列化过程中的错误

说明:

  • 支持直接解析YAML数值
  • 支持解析字符串形式的整数值
  • 解析失败时返回0并记录错误日志

func (Int) Value

func (i Int) Value() (driver.Value, error)

Value 实现driver.Valuer接口,用于数据库写入操作 返回值:

  • driver.Value: 数据库可接受的值
  • error: 转换过程中的错误

type String added in v0.2.2

type String string

String 增强的字符串类型,确保序列化后总是字符串格式

func (String) GetValue added in v0.2.2

func (s String) GetValue() string

GetValue 实现StringValuer[string]接口,获取包装的原始字符串值 返回值:

  • string: 原始的string值

func (String) MarshalJSON added in v0.2.2

func (s String) MarshalJSON() ([]byte, error)

MarshalJSON 实现json.Marshaler接口,将String序列化为JSON字符串 返回值:

  • []byte: 序列化后的JSON字节
  • error: 序列化过程中的错误

说明:确保序列化后总是字符串格式,即使原始值是数值等其他类型

func (String) MarshalYAML added in v0.2.2

func (s String) MarshalYAML() (interface{}, error)

MarshalYAML 实现yaml.Marshaler接口,将String序列化为YAML字符串 返回值:

  • interface{}: 序列化后的值
  • error: 序列化过程中的错误

func (*String) Scan added in v0.2.2

func (s *String) Scan(value interface{}) error

Scan 实现sql.Scanner接口,用于数据库读取操作 参数:

  • value: 从数据库读取的值

返回值:

  • error: 扫描过程中的错误

func (*String) UnmarshalJSON added in v0.2.2

func (s *String) UnmarshalJSON(data []byte) error

UnmarshalJSON 实现json.Unmarshaler接口,支持从JSON字符串或其他类型反序列化为String 参数:

  • data: JSON数据字节

返回值:

  • error: 反序列化过程中的错误

说明:支持从字符串、数值、布尔值等类型反序列化为字符串

func (*String) UnmarshalYAML added in v0.2.2

func (s *String) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML 实现yaml.Unmarshaler接口,支持从YAML字符串或其他类型反序列化为String 参数:

  • node: YAML节点

返回值:

  • error: 反序列化过程中的错误

func (String) Value added in v0.2.2

func (s String) Value() (driver.Value, error)

Value 实现driver.Valuer接口,用于数据库写入操作 返回值:

  • driver.Value: 数据库可接受的值
  • error: 转换过程中的错误

type StringValuer

type StringValuer[T any] interface {
	// GetValue 获取包装的原始值
	GetValue() T
}

StringValuer 定义所有字符串值包装类型的共同泛型接口

Directories

Path Synopsis
-------------------------------- @Create 2025/10/16 11:45 @Author lengpucheng<lpc@hll520.cn> @Project go-strval @Version 1.0.0 2025/10/16 11:45 @Description strval库使用示例 -------------------------------- 本文件展示了如何使用strval库中的Bool、Int和Float类型, 包括JSON和YAML的序列化与反序列化示例。
-------------------------------- @Create 2025/10/16 11:45 @Author lengpucheng<lpc@hll520.cn> @Project go-strval @Version 1.0.0 2025/10/16 11:45 @Description strval库使用示例 -------------------------------- 本文件展示了如何使用strval库中的Bool、Int和Float类型, 包括JSON和YAML的序列化与反序列化示例。

Jump to

Keyboard shortcuts

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