ussd/internal/storage/parse.go

70 lines
939 B
Go
Raw Permalink Normal View History

2025-01-04 09:40:43 +01:00
package storage
2025-01-04 10:37:12 +01:00
import (
"fmt"
"net/url"
"path"
)
2025-01-04 09:40:43 +01:00
const (
DBTYPE_MEM = iota
DBTYPE_GDBM
DBTYPE_POSTGRES
)
type ConnData struct {
2025-01-04 09:40:43 +01:00
typ int
str string
}
func (cd *ConnData) DbType() int {
2025-01-04 10:37:12 +01:00
return cd.typ
}
func (cd *ConnData) String() string {
2025-01-04 10:37:12 +01:00
return cd.str
}
func probePostgres(s string) (string, bool) {
v, err := url.Parse(s)
if err != nil {
return "", false
}
if v.Scheme != "postgres" {
return "", false
}
return s, true
}
func probeGdbm(s string) (string, bool) {
if !path.IsAbs(s) {
return "", false
}
s = path.Clean(s)
return s, true
}
func ToConnData(connStr string) (ConnData, error) {
var o ConnData
2025-01-04 09:40:43 +01:00
2025-01-04 10:37:12 +01:00
if connStr == "" {
return o, nil
2025-01-04 09:40:43 +01:00
}
2025-01-04 10:37:12 +01:00
v, ok := probePostgres(connStr)
if ok {
o.typ = DBTYPE_POSTGRES
o.str = v
return o, nil
}
v, ok = probeGdbm(connStr)
if ok {
o.typ = DBTYPE_GDBM
o.str = v
return o, nil
}
return o, fmt.Errorf("invalid connection string: %s", connStr)
2025-01-04 09:40:43 +01:00
}