Basic abstraction to handle routes

This commit is contained in:
Curt Spark 2025-05-05 22:19:09 +01:00
parent f3ebd2a187
commit bbd15460a3
1 changed files with 32 additions and 15 deletions

47
main.go
View File

@ -11,27 +11,44 @@ import (
"time"
)
type response struct {
Field1 string
Field2 string
}
func main() {
test_response := response{
Field1: "hi",
Field2: "there",
}
http.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Hi, ", r.Header)
result, err := json.Marshal(test_response)
func http_new_route[T any](route string, handle_func func(request *http.Request) (T)) {
http.HandleFunc("/" + route, func(w http.ResponseWriter, r *http.Request) {
result, err := json.Marshal(handle_func(r))
if err != nil {
log.Fatal(err)
}
w.Write(result)
})
}
func main() {
type foo_response_body struct {
Field1 string
Field2 http.Header
}
foo_route_handler := func(request *http.Request) foo_response_body {
fmt.Println(request.Header)
return foo_response_body{
Field1: "hi there on foo!",
Field2: request.Header,
}
}
http_new_route("foo", foo_route_handler)
type bar_response_body struct {
Response int
Message string
}
bar_route_handler := func(request *http.Request) bar_response_body {
return bar_response_body{
Response: 400,
Message: "hi there on bar!",
}
}
http_new_route("bar", bar_route_handler)
http_server := &http.Server{
Addr: ":8080",