-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.go
85 lines (73 loc) · 1.93 KB
/
app.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"time"
)
type app struct {
client apiClient
}
func initApp() (app, error) {
client, err := initApiClient()
a := app{
client: client,
}
return a, err
}
// https://go-acme.github.io/legoHttpReq/dns/httpreq/
type legoHttpReq struct {
FQDN string `json:"fqdn,omitempty"`
Value string `json:"value,omitempty"`
Action string `json:""`
}
func (l legoHttpReq) Validate() error {
if l.FQDN == "" {
return errors.New("Invalid request. fqdn must not be empty")
}
if l.Value == "" {
return errors.New("Invalid request. value must not be empty")
}
return nil
}
func (a app) RequestHandler() func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
l, err := a.processIncomingRequest(r)
if err != nil {
log.Printf("level=warn msg='invalid request' error='%s'\n", err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err = a.client.createTxtRecord(l)
if err != nil {
log.Printf("level=warn msg='create DNS record failed' error='%s'\n", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Printf("level=info msg='request successfully finished' request=%s action=%s domain=%s duration=%.3fs\n", r.RequestURI, l.Action, l.FQDN, time.Since(start).Seconds())
}
}
func (a app) processIncomingRequest(r *http.Request) (legoHttpReq, error) {
var l legoHttpReq
if r.Method != "POST" {
return l, errors.New("invalid method")
}
if r.Body == nil {
return l, errors.New("request with empty body not allowed")
}
err := json.NewDecoder(r.Body).Decode(&l)
if err != nil {
return l, fmt.Errorf("json decoding error: %w", err)
}
if r.RequestURI == "/cleanup" {
l.Action = "DELETE"
} else if r.RequestURI == "/present" {
l.Action = "POST"
} else {
return l, fmt.Errorf("wrong URI: %s", r.RequestURI)
}
return l, l.Validate()
}