dyndns/webapi/server.go
Torben Nehmer 9a31bbc912 - Clarified web handler name
- Implemented Configuration Loader with unauthorized error handling
- More elaborate test user config
- Use Viper Unmarshalling for User Config loading
- Centralized password hasing code
2021-08-22 14:36:55 +02:00

67 lines
1.6 KiB
Go

package webapi
import (
"fmt"
"log"
"net/http"
"gitea.nehmer.net/torben/dyndns/service"
"github.com/gorilla/mux"
)
func Server() {
r := mux.NewRouter()
r.StrictSlash(true)
r.HandleFunc("/hello", handleHello)
r.HandleFunc("/update", handleUpdate)
log.Printf("Listening to: %s", C.ListenAddress)
go log.Fatal(http.ListenAndServe(C.ListenAddress, r))
}
func handleHello(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
log.Printf("handleHello %s", r.Host)
log.Println(r.URL)
log.Println(r.Form.Get("Lorem"))
log.Println(r.Form)
fmt.Fprint(w, "<html><body><p>Hello World</p></body></html>")
}
func handleUpdate(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
ur, err := createUpdateRequestFromForm(r.Form)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
uc, err := service.LoadConfigForUser(ur.UserName, ur.Password)
if err != nil {
if _, ok := err.(*service.UnauthorizedError); ok {
http.Error(w, err.Error(), http.StatusUnauthorized)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
v := uc.DB
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(w, "OK")
fmt.Fprintln(w, ur.PrettyPrint())
log.Println(ur.PrettyPrint())
log.Println(ur.IPv6Net.IP)
log.Println(ur.IPv6Net.Mask)
log.Println(v.AllSettings())
log.Printf("Request PW: %s, Config PW: %s", ur.Password, v.GetString("password"))
fmt.Fprintln(w, "Unmarshalled userconfig:")
fmt.Fprintln(w, uc.PrettyPrint())
}