Server
This commit is contained in:
parent
181a8fa211
commit
95f0719ae1
3 changed files with 56 additions and 5 deletions
16
rex_server/Makefile
Normal file
16
rex_server/Makefile
Normal file
|
@ -0,0 +1,16 @@
|
|||
NAME = rexserver
|
||||
|
||||
build: commit.txt
|
||||
go build -o $(NAME)
|
||||
|
||||
run: commit.txt
|
||||
go run .
|
||||
|
||||
debug: commit.txt
|
||||
go run .
|
||||
|
||||
commit.txt:
|
||||
go generate
|
||||
|
||||
clean:
|
||||
rm -f $(NAME)
|
3
rex_server/go.mod
Normal file
3
rex_server/go.mod
Normal file
|
@ -0,0 +1,3 @@
|
|||
module rex_server
|
||||
|
||||
go 1.23.5
|
|
@ -1,15 +1,47 @@
|
|||
package server
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"encoding/json"
|
||||
"html"
|
||||
"log"
|
||||
"net/http"
|
||||
"rex_model"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
|
||||
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)))
|
||||
})
|
||||
|
||||
http.ListenAndServe(":8080", nil)
|
||||
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)
|
||||
})
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue