pomme/internal/zone.go

85 lines
1.6 KiB
Go

package internal
import (
"errors"
"log"
"net/http"
"strings"
"github.com/miekg/dns"
"gorm.io/gorm"
)
type ZoneRequest struct {
*Zone
User *User `json:"user,omitempty"`
RequestID string `json:"id"`
}
type ZoneResponse struct {
*Zone
User *User `json:"user,omitempty"`
Elapsed int64 `json:"elapsed"`
}
type Zone struct {
ID string `json:"id"`
UserID string `json:"user_id"`
Body string `json:"body"`
}
type User struct {
gorm.Model
Username string `json:"name"`
Password string
HashedPassword string
}
func (zone *ZoneRequest) Parse() error {
zp := dns.NewZoneParser(strings.NewReader(zone.Body), "", "")
for rr, ok := zp.Next(); ok; rr, ok = zp.Next() {
log.Println(rr)
}
if err := zp.Err(); err != nil {
log.Println(err)
return errors.New("unable to parse Zonefile")
}
return nil
}
func (zone *ZoneRequest) Bind(r *http.Request) error {
if zone.Zone == nil {
return errors.New("missing required zone file fields")
}
zone.Zone.Body = strings.ToLower(zone.Zone.Body)
return nil
}
func NewZoneResponse(zone *Zone) *ZoneResponse {
resp := &ZoneResponse{Zone: zone}
if resp.User == nil {
if user, _ := dbGetUser(resp.UserID); user != nil {
resp.User = NewUserPayloadResponse(user)
}
}
return resp
}
func NewUserPayloadResponse(user *User) *User {
return &User{Username: user.Username}
}
func dbGetUser(s string) (*User, error) {
return &User{Username: "user14651"}, nil
}
func (rd *ZoneResponse) Render(w http.ResponseWriter, r *http.Request) error {
// Pre-processing before a response is marshalled and sent across the wire
rd.Elapsed = 10
return nil
}