gotil

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2024 License: MIT Imports: 30 Imported by: 0

README

Gotil

Golang Utility Plugins

Installation

go get -u github.com/nothing2512/gotil

Features

  • Elastic Search
  • Encryption
  • File Uploader
  • HTTP Fetch
  • JSON Parse
  • JSON Stringify
  • Mailer
  • Object To Struct
  • Parse Csv File to Struct
  • Parse Excel File to Struct
  • Parse JSON File to Struct
  • PIN Generator
  • RabbitMQ
  • UUID Generator
  • WebSocket

Example Object to Struct


package main

import (
    "github.com/nothing2512/gotil"
)

type Data struct {
    Name string `customtag:"name"`
}

func main() {
    var data Data
    originalData := map[string]any{
        "name": "Fulan",
    }
    gotil.ParseStruct(&data, originalData, "customtag")
}

Example Send Mail


package main

import (
    "github.com/nothing2512/gotil"
)

type Data struct {
    Name string `json:"name"`
}

func main() {
    m, err := gotil.NewMailer("email", "pass", "host", "port")
	if err != nil {
		panic(err)
	}
	data := Data{"Fulan"}

	m.Subject("subject")

	m.Recipients("mail@gmail.com")
	m.Cc("mail@gmail.com", "mail@gmail.com")
	m.Bcc("mail@gmail.com", "mail@gmail.com")

	m.SetHTMLFile("template.html", data)
	m.AttachFile("certificate.pdf", []byte{})

	err = m.Send()
	if err != nil {
		panic(err)
	}

	m.Close()
}
package main

import (
    "fmt"
    "github.com/nothing2512/gotil"
)

type Test struct {
	ID   int    `json:"id" es:"id"`
	Name string `json:"name" es:"name"`
}

func (*Test) TableName() string {
	return "tests"
}

func main() {
	es, err := gotil.NewElasticSearch("http://0.0.0.0:9200")
    if err != nil {
        panic(err)
    }

	es.Save(&Test{1, "Fulan"})
	es.Save(&Test{2, "Fulan"})
	es.Save(&Test{3, "Fulan"})

	es.Update(&Test{1, "Fulanah"})

	es.Delete(&Test{3, "Fulan"})
	es.DeleteById("tests", 2)

	data := []Test{}
	es.Search(&data, "tests", "fulan", "name", "message")

	for _, x := range data {
		fmt.Println(x.ID, x.Name)
	}
}

Example Rabbit MQ

package main

import (
    "fmt"
    "github.com/nothing2512/gotil"
)

func main() {
	rabbit, err := gotil.NewRabbitMQ("rabbitmq_user", "rabbitmq_password", "0.0.0.0", "5672")
	if err != nil {
		panic(err)
	}
	rabbit.Publish("channel1", "Hello, RabbitMQ World!")
	rabbit.Consume("channel1", func(data string) {
		fmt.Println(data)
	})
}

Example HTTP Fetch


package main

import (
    "github.com/nothing2512/gotil"
)

type Response struct {
	Status	bool `json:"status"`
	Message	string `json:"message"`
	Data 	gotil.JSON `json:"data"`
}

func main() {
	var data Data
	f := gotil.HTTPFetcher{
		Method: "POST",
		Url: "",
		Headers: gotil.JSON{},
		Body: gotil.JSON
	}
	err := f.fetch(&data)
}

Example Web Socket

  • server.go
package main

import (
	"fmt"

	"github.com/nothing2512/gotil"
)

func main() {
	ws := gotil.NewWebSocket("0.0.0.0:8080")

	// Server Handle Incoming Command
	ws.OnCommand(func(m gotil.WebSocketMessage) {
		fmt.Println(m.Command, m.Message)

		// Server Send Reply Message
		ws.Reply(m, "Reply Message")

		// Server blast to all connection
		ws.Blast("Blast Message")
	})

	// Start Server
	err := ws.Server("00000000000000000000000000000000", "1111111111111111")
	if err != nil {
		panic(err)
	}
}
  • client.go
package main

import (
	"fmt"

	"github.com/nothing2512/gotil"
)

func main() {
	ws := gotil.NewWebSocket("0.0.0.0:8080")

	// Start Client
	err := ws.Client()
	if err != nil {
		panic(err)
	}

	// Client Handle Incoming Message
	ws.OnMessage(func(m gotil.WebSocketMessage) {
		fmt.Println(m.Message)
	})

	// Client Send Message To Other Client
	ws.Send("target-uid", "Hello")

	// Client Send Command To server
	ws.Command(gotil.WebSocketMessage{
		Command: "cmd",
		Message: "msg",
	})
}
  • Send trough HTTP
POST /send HTTP/1.1
Host: 0.0.0.0:8080
Content-Type: application/json
Content-Length: 237

{
    "token": "32097440af2b367064e37c43f08821daddb6ece61de2f4a8bb5a205bb75f3a9fdc27ea70",
    "to": "5fe7d69e-9432-86a0-0585-fd7c11c39e71",
    "command": "command|send",
    "message": "{\"command\":\"cmd\",\"message\": \"message\"}"
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func JsonParse added in v1.0.1

func JsonParse(obj any, data string) error

parse json string to map / slice / struct

func JsonStringify added in v1.0.1

func JsonStringify(data any) string

Convert map / struct / slice to string

func PIN

func PIN(length int) string

generate pin with given length

func ParseCSVFile

func ParseCSVFile(filename string, result any) error

parsing csv file to struct / map / slice

func ParseExcelFile

func ParseExcelFile(filename string, result any) error

parsing excel file to struct / map / slice

func ParseJSONFile

func ParseJSONFile(filename string, result any) error

parsing json file to struct / map / slice

func ParseStruct

func ParseStruct(obj any, data any, tag string) error

parse map data to struct with custom struct tag

func UUID

func UUID() string

generate uuid

func Upload

func Upload(location string, file multipart.File, header *multipart.FileHeader) string

http upload file

Types

type Elastable

type Elastable interface {
	TableName() string
}

Elastic Search Table Interface

type ElasticClient

type ElasticClient struct {
	// contains filtered or unexported fields
}

Base Elastic Client Struct

func NewElasticSearch

func NewElasticSearch(uri string) (*ElasticClient, error)

Create new Elastic Client

func (*ElasticClient) Delete

func (ec *ElasticClient) Delete(data Elastable) error

Delete Data By Model

func (*ElasticClient) DeleteById

func (ec *ElasticClient) DeleteById(table string, id any) error

Delete Data by Id

func (*ElasticClient) Save

func (ec *ElasticClient) Save(data Elastable) error

create new data

func (*ElasticClient) Search

func (ec *ElasticClient) Search(obj any, table, value string, keys ...string)

search data

func (*ElasticClient) Update

func (ec *ElasticClient) Update(data Elastable) error

Update Data by model

type Encryption

type Encryption struct {
	// contains filtered or unexported fields
}

basae encryption model

func DefaultEncryption

func DefaultEncryption() *Encryption

generate default encryption

func NewEncryption

func NewEncryption(secret, iv string) *Encryption

generate new encryption

func (*Encryption) Decrypt

func (e *Encryption) Decrypt(data string) string

decrypt data

func (*Encryption) Encrypt

func (e *Encryption) Encrypt(data string) string

encrypt data

type HTTPFetcher

type HTTPFetcher struct {
	Method  string
	Url     string
	Body    JSON
	Headers JSON
}

base http fetcher

func (HTTPFetcher) Fetch

func (h HTTPFetcher) Fetch(result any) error

fetch http

type JSON

type JSON map[string]interface{}

JSON types

type Mailer

type Mailer struct {
	// contains filtered or unexported fields
}

mailer base model

func NewMailer

func NewMailer(email, password, host, port string) (*Mailer, error)

crate new mailer

func (*Mailer) AttachFile

func (m *Mailer) AttachFile(filename string, data []byte) error

attach file to mail

func (*Mailer) Bcc

func (m *Mailer) Bcc(emails ...string)

set bcc emails

func (*Mailer) Cc

func (m *Mailer) Cc(emails ...string)

set cc emails

func (*Mailer) Close

func (m *Mailer) Close()

func (*Mailer) From

func (m *Mailer) From(from string)

set sender email

func (*Mailer) Recipients

func (m *Mailer) Recipients(emails ...string)

set mail recipients

func (*Mailer) Send

func (m *Mailer) Send() error

send email

func (*Mailer) SetHTML

func (m *Mailer) SetHTML(content string) error

set mail html content

func (*Mailer) SetHTMLFile

func (m *Mailer) SetHTMLFile(file string, data any) error

set mail html file with data

func (*Mailer) SetText

func (m *Mailer) SetText(text string) error

set mail text content

func (*Mailer) Subject

func (m *Mailer) Subject(subject string)

set mail subject

type RabbitMQ

type RabbitMQ struct {
	// contains filtered or unexported fields
}

rabbit mq base model

func NewRabbitMQ

func NewRabbitMQ(user, pass, host, port string) (*RabbitMQ, error)

create new rabbit mq instance

func (*RabbitMQ) Consume

func (r *RabbitMQ) Consume(channel string, action func(data string)) error

consume channel from client

func (*RabbitMQ) Publish

func (r *RabbitMQ) Publish(channel, data string) error

publish message in channel

type WebSocket

type WebSocket struct {
	// contains filtered or unexported fields
}

websocket base model

func NewWebSocket

func NewWebSocket(baseUri string) *WebSocket

Create New Websocket

func (*WebSocket) AuthorizeNewClient added in v1.0.2

func (s *WebSocket) AuthorizeNewClient(authorizeNewClient func(token string) bool)

Server Must Authorize New Client

func (*WebSocket) Blast

func (s *WebSocket) Blast(m string) error

Server Blast Message

func (*WebSocket) Client

func (s *WebSocket) Client() error

Start Client

func (*WebSocket) Command

func (s *WebSocket) Command(data WebSocketMessage) error

Client Send Command

func (*WebSocket) Disconnect

func (s *WebSocket) Disconnect() error

Disconnect Client

func (*WebSocket) OnCommand

func (s *WebSocket) OnCommand(handle func(m WebSocketMessage))

Handle Command On Server

func (*WebSocket) OnMessage

func (s *WebSocket) OnMessage(handle func(m WebSocketMessage))

Client On Message Received

func (*WebSocket) Reply

func (s *WebSocket) Reply(m WebSocketMessage, message string) error

Server Send Reply Message

func (*WebSocket) Send

func (s *WebSocket) Send(to string, msg string) error

Client Send Message To Other

func (*WebSocket) Server

func (s *WebSocket) Server(secret, iv string) error

Start Server

type WebSocketMessage

type WebSocketMessage struct {
	Command string `json:"command"`
	Message string `json:"message"`
	Token   string `json:"token"`
	To      string `json:"to"`
}

web socket base message model

Jump to

Keyboard shortcuts

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