package main

import (
	"fmt"
	"regexp"
)

type postgres struct {
	user    string
	pass    string
	host    string
	port    string
	name    string
	table   string
	options []string
}

func main() {
	str := "postgres://pgusername:pguserpass@pghostip:5432/pgdbname"
	fmt.Println(decodePostgreSQLURI(str))
}

func decodePostgreSQLURI(pguri string) (p postgres) {
	pattern := "postgres://(?P<dbuser>.*):(?P<dbpass>.*)@(?P<dbhost>.*):(?P<dbport>[0-9]+)/(?P<dbname>.*)"

	re := regexp.MustCompile(pattern)
	match := re.FindStringSubmatch(pguri)
	pm := make(map[string]string)
	for i, name := range re.SubexpNames() {
		if i > 0 && i <= len(match) {
			pm[name] = match[i]
			//fmt.Println(i, ":", name, ":", match[i])
		}
	}
	p.user = pm["dbuser"]
	p.pass = pm["dbpass"]
	p.host = pm["dbhost"]
	p.port = pm["dbport"]
	p.name = pm["dbname"]
	return p
}