sync. refactoring for code re-use

This commit is contained in:
Josh Ashton
2024-08-04 18:31:31 -06:00
parent 22e14fe11d
commit 3e94d5c8ba
4 changed files with 320 additions and 226 deletions
@@ -0,0 +1,42 @@
package main
import (
"github.com/gorilla/mux"
"log"
"net/http"
"time"
)
// Serve an API using mux.Router().Host({domain}).Subrouter().
// Provide the router, domain, an array of endpoints and functions, and
// the port you would like the API accessible to.
func serveApi(
router *mux.Router,
domain string,
endpoint []string,
function []func(http.ResponseWriter, *http.Request),
port int,
) {
// TODO: Add error handling
apiR := router.Host(domain).Subrouter()
for i := 0; i < len(endpoint); i++ {
apiR.HandleFunc(endpoint[i], function[i])
}
apiSrv := &http.Server{
Addr: "0.0.0.0:" + string(port),
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
Handler: apiR,
}
go func() {
if err := apiSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Println(err)
}
}()
log.Println("API server is running on port " + string(port))
}