67 lines
1.3 KiB
Go
67 lines
1.3 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
)
|
|
|
|
func init() {
|
|
http.HandleFunc("/present", present)
|
|
http.HandleFunc("/cleanup", cleanup)
|
|
}
|
|
|
|
type request struct {
|
|
FQDN string `json:"fqdn"`
|
|
Value string `json:"value"`
|
|
}
|
|
|
|
func httpCommon(res http.ResponseWriter, req *http.Request, fn func(request)) {
|
|
if req.Method != http.MethodPost {
|
|
res.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
user, _, basicAuthOk := req.BasicAuth()
|
|
if !basicAuthOk {
|
|
fmt.Printf("basic auth failed\n")
|
|
res.WriteHeader(http.StatusForbidden)
|
|
return
|
|
}
|
|
|
|
body := request{}
|
|
d := json.NewDecoder(req.Body)
|
|
d.DisallowUnknownFields()
|
|
if err := d.Decode(&body); err != nil {
|
|
res.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if d.More() {
|
|
res.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if user != body.FQDN {
|
|
fmt.Printf("expected %s == %s\n", user, body.FQDN)
|
|
res.WriteHeader(http.StatusForbidden)
|
|
return
|
|
}
|
|
|
|
fn(body)
|
|
}
|
|
|
|
func present(res http.ResponseWriter, req *http.Request) {
|
|
httpCommon(res, req, func(body request) {
|
|
fmt.Printf("add %s to %s\n", body.Value, body.FQDN)
|
|
db.Add(body.FQDN, body.Value)
|
|
})
|
|
}
|
|
|
|
func cleanup(res http.ResponseWriter, req *http.Request) {
|
|
httpCommon(res, req, func(body request) {
|
|
fmt.Printf("remove %s from %s\n", body.Value, body.FQDN)
|
|
db.Remove(body.FQDN, body.Value)
|
|
})
|
|
}
|