package main import ( "encoding/json" "fmt" "log" "net/http" "os" "os/signal" "syscall" "time" ) 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", Handler: nil, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } go func() { log.Fatal(http_server.ListenAndServe()) }() fmt.Println("Server started! Listening in on ", http_server.Addr) sigs := make(chan os.Signal, 1) signal.Notify(sigs, os.Interrupt, syscall.SIGTERM) <-sigs fmt.Println("Server stopped!") os.Exit(1) }