simple

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2025 License: MIT Imports: 33 Imported by: 0

README

Simple package

Simple is a Go package providing utilities tasks in order to reduces boilerplate code. Each file represent a feature

Features

ORM for database management

  • Choose your preferred driver: MySQL, PostgreSQL, or SQLite
  • Or use GetEnv() to use environnement variable for connection credentials
  • Simple methods: Migrate(), GetRowBy(), GetRows(), UpdateRowBy(), DeleteRowBy() and CountRows()

Example :

var ctx context.Context

db, err := OpenDatabase(GetSqlite("path/to/my/database.db"))
if err != nil {
    fmt.Println(err)
}

book, err := GetRowBy[&Book](ctx, db, "title", "The Go Programming Language Phrasebook")
if err != nil {
    fmt.Println(err)
} else {
    fmt.Println(book.Title)
}

Using GetEnv() :

type Config struct {
	DbName string	`env:"POSTGRES_DB"`
	DbUser string	`env:"POSTGRES_USER"`
	DbPass string	`env:"POSTGRES_PASSWORD"`
	Port string		`env:"POSTGRES_PORT"`
}

cfg, err := GetEnv[Config](".env")
if err != nil {
   fmt.Println(err)
}

db, err := OpenDatabase(GetPostgres("localhost", cfg.DbUser, cfg.DbPass, cfg.DbName, 5432, "Europe/Paris"))
if err != nil {
    fmt.Println(err)
}

Web client management: :

  • Choose the client of your choice : http, Tor sock, your own proxy...
  • Fetch raw or pased HTML content
  • Download files with DownloadDocument(), and with automatic sha-256 hash computation via DownloadDocumentReturnHash().

Example :

var ctx context.Context
body, err := GetContent(ctx, "https://golangdocs.com", HttpClient(), nil)
if err != nil {
    fmt.Println(err)
}

hash, err := DownloadDocumentReturnHash(ctx, "https://golangdocs.com/how-to-install-go-on-a-vps-server", "storage/file.html", HttpClient(), nil)
if err != nil {
    fmt.Println(err)
} else {
    fmt.Println(hash)
}

//Custom request
body, err := GetContent(ctx, "https://example.com/api", HttpClient(), func(req *http.Request) error {
	req.Header.Set("User-Agent", "Go-http-client/1.1")
	req.Header.Set("Accept", "*/*")
    return nil
})
if err != nil {
    fmt.Println(err)
}

Hash functions

  • Supported algorithms:
    • sha-224, sha-256, sha-384, sha-512 and sha3 family
    • shake (128, 256)
    • blake2b (256, 384, 512) and blake2s (128, 256)
    • legacy : md5 and sha1
  • File hashing
  • Compare files or hash arbitrary data.

Example :

sha_hash, err := HashFile("sha3-512", "storage/file.html")
if err != nil {
    fmt.Println(err)
} else {
    fmt.Println(sha_hash)
}

blake_hash, err := HashFileKey("blake2b-384", "mykey", "storage/file.html")
if err != nil {
    fmt.Println(err)
} else {
    fmt.Println(blake_hash)
}

File

  • Deserialization :
    • one function for multiple file format support (json, yaml, toml and xml)
    • Use limit parameter to deserialize only a specific amount of elements
    • Set validation to true in order to apply tag validation from validator package

Example :

data_json, err := LoadFile[DataJson]("test.json", 0, false)
if err != nil {
    fmt.Println(err)
} else {
    fmt.Println(data_json)
}

data_yaml, err = LoadFile[DataYaml]("test2.yaml", 0, true)
if err != nil {
    fmt.Println(err)
} else {
    fmt.Println(data_json)
}

err = Unzip()

Development

v0 :

  • add first features : Orm, Hash, Requests, File, Env
  • add tests/ folder for mock and unit tests
  • add Readme, MIT License, Changelog
  • Code correction + comments + cleaning

v1 :

  • add context for Orm and Requests
  • New feature on File : Unzip()
  • Improved ORM functions

Dependencies

  • Requests features are based on Go’s standard net/http package
  • Hash features are based on Go’s standard crypto package
  • Orm features are based on
  • Deserialize features are based on

Documentation

Index

Constants

This section is empty.

Variables

View Source
var FileRegistry = map[string]FileParser{
	"json": json.Unmarshal,
	"yaml": yaml.Unmarshal,
	"toml": toml.Unmarshal,
	"xml":  xml.Unmarshal,
}
View Source
var Registry = map[string]func() hash.Hash{
	"sha256":   sha256.New,
	"sha384":   sha512.New384,
	"sha512":   sha512.New,
	"sha3-224": sha3.New224,
	"sha3-256": sha3.New256,
	"sha3-384": sha3.New384,
	"sha3-512": sha3.New512,
	"shake-128": func() hash.Hash {
		return &shakeAdapter{shake: sha3.NewShake128(), length: 32}
	},
	"shake-256": func() hash.Hash {
		return &shakeAdapter{shake: sha3.NewShake256(), length: 64}
	},
}
View Source
var RegistryKey = map[string]HashKeyFactory{
	"blake2b-256": func(key []byte) (hash.Hash, error) {
		return blake2b.New256(key)
	},
	"blake2b-384": func(key []byte) (hash.Hash, error) {
		return blake2b.New384(key)
	},
	"blake2b-512": func(key []byte) (hash.Hash, error) {
		return blake2b.New512(key)
	},
	"blake2s-128": func(key []byte) (hash.Hash, error) {
		return blake2s.New128(key)
	},
	"blake2s-256": func(key []byte) (hash.Hash, error) {
		return blake2s.New256(key)
	},
}
View Source
var RegistryLegacy = map[string]func() hash.Hash{
	"md5":  md5.New,
	"sha1": sha1.New,
}

Legacy hash not supported yet.

Functions

func CompareFiles

func CompareFiles(hash string, fileA string, fileB string) (bool, error)

compare two files

func CompareFilesKey

func CompareFilesKey(hash string, keyA []byte, fileA string, keyB []byte, fileB string) (bool, error)

func CountRows added in v1.1.0

func CountRows[T any](ctx context.Context, db *gorm.DB) (int64, error)

Counts how much rows there is in your given table `T`

func DeleteRowBy added in v1.1.0

func DeleteRowBy[T any](ctx context.Context, db *gorm.DB, key string, value any) error

Deletes rows where column `key` equals `value`

func DownloadDocument added in v0.2.3

func DownloadDocument(ctx context.Context, url string, filePath string, client *http.Client, req CustomReq) error

download a document give the url, the filepath where you want to store the document and the client

func DownloadDocumentReturnHash

func DownloadDocumentReturnHash(ctx context.Context, url string, filePath string, client *http.Client, req CustomReq) (string, error)

download a document and return its hash value

func GetColumn added in v0.2.7

func GetColumn[T any, C any](ctx context.Context, odb *gorm.DB, columnName string) ([]C, error)

GetColumn returns a specific column of your table `T`of type `C`.

func GetContent

func GetContent(ctx context.Context, url string, client *http.Client, req CustomReq) ([]byte, error)

Get the body of a webpage. Give the url and it will return the html body

func GetEnv added in v1.2.0

func GetEnv[T any](filename string) (*T, error)

GetEnv retrieve the env var in your .env file Give a struct, as a generic, with the following tag : `env:"VARIABLE_NAME"` beside each fields.

func GetMysql added in v0.2.3

func GetMysql(user, password, host, port, dbName string) (string, string)

Get a mysql string with its associate dns for fast connection

func GetParsedContent

func GetParsedContent(ctx context.Context, url string, client *http.Client, req CustomReq) (*html.Node, error)

Get the body and parse it. The package net/html allow to parse a html body into nodes to easily retrieve every html tags

func GetPostgres added in v0.2.3

func GetPostgres(host, user, password, dbName, port string) (string, string)

Get a postgres string with its associate dns for fast connection

func GetRowBy added in v1.1.0

func GetRowBy[T any](ctx context.Context, db *gorm.DB, key string, value any) (*T, error)

GetRowBy returns the first record of type T where column `key` equals `value`.

func GetRowsBy added in v1.1.1

func GetRowsBy[T any](ctx context.Context, db *gorm.DB, key string, value any) ([]T, error)

GetRowsBy returns every record of type T where column `key` equals `value`.

func GetSqlite added in v0.2.3

func GetSqlite(filePath string) (string, string)

Get a mysql string with its associate dns for fast connection Specify either the path of your file or open it in memory

func GetTable added in v0.2.6

func GetTable[T any](ctx context.Context, db *gorm.DB, limit int) ([]T, error)

GetTable return every rows of the given table `T` Set the limit of rows with `limit`. Use -1 to get every rows

func HashData

func HashData(hash string, data []byte) (string, error)

hash a given byte string

func HashFile

func HashFile(hash, filePath string) (string, error)

hash a file with the given hash algorithm

func HashFileKey

func HashFileKey(hash string, key []byte, filePath string) (string, error)

hash a file with the given hash algorithm from the RegistryKey

func HttpClient

func HttpClient() *http.Client

http client Default config

func LoadFile added in v0.2.5

func LoadFile[S any](filePath string, limit int, validation bool) ([]S, error)

Deserialize data from the given data type (json, yaml, toml or xml)

func Migrate added in v0.2.6

func Migrate(ctx context.Context, odb *gorm.DB, models ...any) error

Database migration.

func OnionClient

func OnionClient() (*http.Client, error)

onion client Default config

func OpenDatabase

func OpenDatabase(driver, dsn string) (*gorm.DB, error)

Open a database with custom dsn or use function GetMysql(), GetPostgres() anb GetSqlite()

func Unzip added in v1.0.1

func Unzip(ctx context.Context, source, destination string) error

Adapted from Gosamples website

func UpdateRowBy added in v1.1.0

func UpdateRowBy[T any](ctx context.Context, db *gorm.DB, key string, value any, field string, newValue any) error

Updates rows where column `key` equals `value`

Types

type CustomReq added in v1.0.2

type CustomReq func(*http.Request) error

type FactoryDB added in v0.2.7

type FactoryDB func(dsn string) gorm.Dialector

type FileParser added in v0.2.5

type FileParser func([]byte, any) error

type HashKeyFactory

type HashKeyFactory func(key []byte) (hash.Hash, error)

Jump to

Keyboard shortcuts

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