47 lines
1.1 KiB
Go
47 lines
1.1 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"html"
|
|
"log"
|
|
"net/http"
|
|
"rex_model"
|
|
"time"
|
|
)
|
|
|
|
func main() {
|
|
port := ":8080"
|
|
addons := rex_model.AddonIndex
|
|
|
|
mux := http.NewServeMux()
|
|
|
|
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
|
_, _ = w.Write([]byte("Hello, " + html.EscapeString(r.URL.Path)))
|
|
})
|
|
|
|
mux.HandleFunc("/api/index", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
if err := json.NewEncoder(w).Encode(addons); err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
})
|
|
|
|
loggedMux := loggingMiddleware(mux)
|
|
|
|
log.Printf("Listening on http://localhost%s", port)
|
|
log.Fatal(http.ListenAndServe(port, loggedMux))
|
|
}
|
|
|
|
func loggingMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
|
|
log.Printf("[%s] %s %s %s", r.RemoteAddr, r.Method, r.URL.Path, start.Format("2006-01-02 15:04:05"))
|
|
|
|
next.ServeHTTP(w, r)
|
|
duration := time.Since(start)
|
|
|
|
log.Printf("[%s] Completed in %v\n", r.RemoteAddr, duration)
|
|
})
|
|
}
|