package rules import ( "encoding/json" "fmt" "log" "git.beisel.it/florian/hostname-service/db" ) type HostnameRule interface { Generate(params map[string]interface{}) (string, []byte, error) Insert(category string, params map[string]interface{}) (string, error) Update(category string, oldhostname string, params map[string]interface{}) (string, error) } type BaseRule struct{} func (br *BaseRule) baseInsert(rule HostnameRule, category string, params map[string]interface{}) (string, error) { // Generate the hostname using the passed rule's Generate method hostname, paramsJSON, err := rule.Generate(params) if err != nil { return "", err } exists, err := db.HostnameExists(category, hostname) if err != nil { log.Printf("error checking existence of hostname: %v", err) return "", err } if exists { log.Printf("hostname %s does not exist in category %s", hostname, category) return "", fmt.Errorf("hostname-exists") } // Insert the hostname into the database err = db.InsertHostname(category, hostname, paramsJSON) if err != nil { log.Printf("Error inserting hostname into DB: %v", err) return "", err } return hostname, nil } // baseUpdate method for BaseRule func (br *BaseRule) baseUpdate(rule HostnameRule, category string, oldhostname string, params map[string]interface{}) (string, error) { // Generate the new hostname using the passed rule's Generate method newHostname, paramsJSON, err := rule.Generate(params) if err != nil { return "", err } // Update the hostname in the database err = db.UpdateHostname(category, oldhostname, newHostname, paramsJSON) if err != nil { log.Printf("Error updating hostname in DB: %v", err) return "", err } return newHostname, nil } func StructToJSON(v interface{}) (string, error) { bytes, err := json.Marshal(v) if err != nil { return "", err } return string(bytes), nil }