INT 21h

Hi, I am Vladimir Smagin, SysAdmin and Kaptain. Telegram Email / GIT / RSS / GPG

Golang: marshal and unmarshal iota (yaml, json, toml)

№ 11025 В разделе Programming от June 16th, 2020,
В подшивках:

Tried to unmarshal enum value from app config file and failed?

DB:
  masterDB: "ips.sdb"
  clean: Full

Use strings instead of iota.

const (
	CleanRecreate  = "Recreate" // completely remove DB file and create again
	CleanFull      = "Full" // delete all and vacuum
	CleanLastDay   = "LastDay" // remove all before last day
	CleanLastWeek  = "LastWeek"
	CleanLastMonth = "LastMonth"
	CleanNever     = "Never" // do nothing
)

type CleanType string

type AppConfig struct {
	DB    struct {
		MasterDB string    `yaml:"masterDB"`        // master sqlite database
		Clean    CleanType `yaml:"clean,omitempty"` // cleanup at startup
	} `yaml:"DB"`
}

Now load config file:

func main() {
	flag.Parse()
	if *configFilename == "" {
		log.Fatalln("Set configuration filename")
	}

	// read settings from file
	log.Println("Loading config file", *configFilename)
	appConfig := AppConfig{}

	yamlFile, err := ioutil.ReadFile(*configFilename)
	if err != nil {
		log.Fatalf("Config read error: %v\n", err)
	}
	err = yaml.Unmarshal(yamlFile, &appConfig)
	if err != nil {
		log.Fatalf("Config format error: %v\n", err)
	}

	switch appConfig.DB.Clean {
	case CleanRecreate:
		log.Println("Recreate cleanup option set")
		os.Remove(appConfig.DB.MasterDB)
	case CleanFull:
		log.Println("Full cleanup option set")
	case CleanLastDay:
		log.Println("Save only last day cleanup option set")
	case CleanLastWeek:
		log.Println("Save only last week option set")
	case CleanLastMonth:
		log.Println("Save only last month option set")
	}
	dbHandler := dbLoadFile(appConfig.DB.MasterDB)
	defer dbHandler.Close()
}

Here is another solution https://gist.github.com/lummie/7f5c237a17853c031a57277371528e87#file-enum-go

Нет комментариев »

Простой способ подготовки библиотеки на golang к тестированию

№ 11006 В разделе Programming от May 26th, 2020,
В подшивках:

Чтобы без проблем тестировать программы, написанные с использованием вашей библиотеки ее необходимо подготовить для этого. Делаем интерфейс, который будет использоваться в тестах, где ваши реальные функции будут заменены функциями с тестовыми данными.

package main

import "fmt"

// library 

type FooAdapter interface {
	Read() string
}

type Foo struct {
	mvar    string
}

func NewFoo(v string) FooAdapter {
	return &Foo{mvar:v}
}

func (a *Foo) Read() string {
	return "orig: " + a.mvar
}

// test 

func NewFooStub(v string) FooAdapter {
	return &FooStub{mvar: v}
}

type FooStub struct {
	mvar string
}

func (s *FooStub) Read() string {
	return "stub: " + s.mvar
}

func main() {
	z := NewFoo("o")
	fmt.Println("Read", z.Read())
	m := NewFooStub("s")
	fmt.Println("Read", m.Read())
}

https://play.golang.org/p/9utaWeDjNjo

Нет комментариев »

Hetzner DNS golang library

№ 10996 В разделе Programming от May 6th, 2020,
В подшивках: ,

I made this library to interact with Hetzner DNS API in most easy way. Hopefully in future it will be used for Hetzner external-dns provider. Check out example directory and API_help.md.

Get your own token on Hetzner DNS and place it to token variable and run code

token := "jcB2UywP9XtZGhvhSHpH5m"
zone := "vhSHpH5mjcB2UywP9XtZGh"

log.Println("Create new instance")
hdns := hclouddns.New(token)

log.Println("Get zone", zone)

allRecords, err := hdns.GetRecords(zone)
if err != nil {
	log.Fatalln(err)
}

log.Println(allRecords.Records)
log.Println(allRecords.Error)

Нет комментариев »

CronJobs operator for Kubernetes

№ 10306 В разделах: Programming Sysadmin от September 17th, 2019,
В подшивках: , , ,

Helps to control multiple cronjobs with same image, but different commands.

Checkout code and documentation https://git.blindage.org/21h/cron-operator

Нет комментариев »

Vault secret retrieve and save to JSON file

№ 10280 В разделах: Programming Sysadmin от September 1st, 2019,
В подшивках: , ,

I wrote small program to retrieve secrets from Vault and provide them to my PHP and Python apps. ENV variables with connection credentials is useful with Docker containers and even Kubernetes, list of secrets to retrieve can be stored inside Docker image.

Secret stored in Vault

Result file on disk

Source code and binary release https://git.blindage.org/21h/vault-retriever

Нет комментариев »

Облачная платформа
Яндекс.Метрика

Fortune cookie: Q: How did you get into artificial intelligence? A: Seemed logical -- I didn't have any real intelligence.