Basic abstraction to handle routes
This commit is contained in:
parent
f3ebd2a187
commit
bbd15460a3
47
main.go
47
main.go
|
|
@ -11,27 +11,44 @@ import (
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type response struct {
|
func http_new_route[T any](route string, handle_func func(request *http.Request) (T)) {
|
||||||
Field1 string
|
http.HandleFunc("/" + route, func(w http.ResponseWriter, r *http.Request) {
|
||||||
Field2 string
|
result, err := json.Marshal(handle_func(r))
|
||||||
}
|
|
||||||
|
|
||||||
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)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
w.Write(result)
|
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{
|
http_server := &http.Server{
|
||||||
Addr: ":8080",
|
Addr: ":8080",
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue