You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.7 KiB

package main
import (
"encoding/json"
"log"
"net/http"
"os"
"strings"
)
//NewHTTPHandler creates a new http handler
func NewHTTPHandler(cfg Configuration, bm BlocklistManager) http.Handler {
return newAPIHandler(nil, cfg, bm)
}
func newAPIHandler(inner http.Handler, cfg Configuration, bm BlocklistManager) http.Handler {
l := log.New(os.Stdout, "[HTTP API] ", log.LUTC|log.Lshortfile)
apiHandler := http.NewServeMux()
/*
1. update block lists
*/
apiHandler.HandleFunc("/blocklists/reload", func(w http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
http.Error(w, "method not allowed, must be a POST", http.StatusMethodNotAllowed)
return
}
if err := bm.Reload(req.Context()); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
l.Println("reloaded blocklists successfully")
})
apiHandler.HandleFunc("/config", func(w http.ResponseWriter, req *http.Request) {
switch req.Method {
case http.MethodGet:
w.Header().Set("Content-Type", "application/json")
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
if err := encoder.Encode(cfg); err != nil {
log.Printf("could not send config: %v", err)
}
default:
http.Error(w, "method not allowed, must be a POST", http.StatusMethodNotAllowed)
}
})
h := http.StripPrefix("/api/gopherhole", apiHandler)
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if strings.HasPrefix(req.URL.Path, "/api/gopherhole") {
h.ServeHTTP(res, req)
return
}
handleDefaultRequests(res, req)
})
}
func handleDefaultRequests(res http.ResponseWriter, req *http.Request) {
log.Printf("got request for: %s", req.URL.Hostname())
}