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, prefix string, endpoints []string, methods []string, functions []func(http.ResponseWriter, *http.Request), port string, ) { apiR := router.PathPrefix(prefix).Subrouter() for i := range endpoints { apiR.HandleFunc(endpoints[i], functions[i]).Methods(methods[i]) } apiR.Use(auth_middleware) apiSrv := &http.Server{ Addr: "0.0.0.0:" + 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 " + port) }