add a response type and pass back errors

This commit is contained in:
Aaron Bieber 2024-08-23 08:51:31 -06:00
parent 259060aa74
commit 94a5f9c8da
No known key found for this signature in database
3 changed files with 32 additions and 14 deletions

22
main.go
View File

@ -77,15 +77,18 @@ func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
httpLog(r)
if err := records.templ.ExecuteTemplate(w, "index", records); err != nil {
resp := &Response{}
resp.Entries = records.Entries
if err := records.templ.ExecuteTemplate(w, "index", resp); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
mux.HandleFunc("POST /records", func(w http.ResponseWriter, r *http.Request) {
httpLog(r)
resp := &Response{}
ipStr := r.FormValue("ip")
ip := net.ParseIP(ipStr)
if ip != nil {
rec := Record{
Name: r.FormValue("name"),
IP: ip,
@ -93,24 +96,27 @@ func main() {
records.Entries = append(records.Entries, rec)
records.Save(*dataDir)
} else {
resp.Error = fmt.Errorf("invalid IP: %q", ipStr)
}
if err := records.templ.ExecuteTemplate(w, "table", records); err != nil {
resp.Entries = records.Entries
if err := records.templ.ExecuteTemplate(w, "table", resp); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
mux.HandleFunc("DELETE /records/{name}", func(w http.ResponseWriter, r *http.Request) {
httpLog(r)
resp := Response{}
records.Delete(r.PathValue("name"))
records.Save(*dataDir)
if err := records.templ.ExecuteTemplate(w, "table", records); err != nil {
resp.Entries = records.Entries
if err := records.templ.ExecuteTemplate(w, "table", resp); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
mux.HandleFunc("PUT /records/{name}", func(w http.ResponseWriter, r *http.Request) {
httpLog(r)
})
httpServer := &http.Server{
Handler: mux,

View File

@ -12,6 +12,11 @@ import (
"github.com/miekg/dns"
)
type Response struct {
Error error `json:"error"`
Entries []Record `json:"entries"`
}
type Record struct {
Name string `json:"name"`
IP net.IP `json:"ip"`

View File

@ -23,7 +23,6 @@
</style>
</head>
<body>
<h1>tsns</h1>
<hr/>
@ -48,7 +47,15 @@
{{ template "row" . }}
{{ end }}
</tbody>
<tfoot>
<tr>
<td>
<div id="error" >{{ .Error }}</div>
</td>
</tr>
</tfoot>
</table>
{{ end }}
{{ block "row" . }}