Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions hyperdrive.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"fmt"
"log"
"net/http"
"time"

"github.com/caarlos0/env"
"github.com/gorilla/handlers"
Expand All @@ -24,13 +25,21 @@ import (
// to the response handlers using a gorlla mux Router.
type API struct {
Router *mux.Router
Server *http.Server
conf Config
endpoints []Endpoint
}

// NewAPI creates an instance of an API with an initialized Router.
func NewAPI() API {
NewConfig()
return API{Router: mux.NewRouter()}
api := API{Router: mux.NewRouter(), conf: NewConfig()}
api.Server = &http.Server{
Handler: api.Router,
Addr: api.conf.GetPort(),
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
return api
}

// AddEndpoint registers endpoints, ensuring that endpoints automatically
Expand Down Expand Up @@ -65,6 +74,13 @@ func (api *API) AddEndpoint(e Endpointer) {
api.Router.HandleFunc(e.GetPath(), handler.ServeHTTP)
}

// Start starts the configured http server, listening on the configured Port
// (default: 5000). Set the PORT environment variable to change this.
func (api *API) Start() {
log.Printf("Hyperdrive API starting on PORT %d", api.conf.Port)
log.Fatal(api.Server.ListenAndServe())
}

// GetHandler interface is satisfied if the endpoint has implemented
// a http.Handler method called Get(). If this is not implemented,
// GET requests will be responded to with a `405 Method Not Allowed`
Expand Down
5 changes: 5 additions & 0 deletions hyperdrive_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package hyperdrive

import (
"net/http"
"os"
"testing"

Expand All @@ -20,6 +21,10 @@ func (suite *HyperdriveTestSuite) TestNewAPI() {
suite.IsType(API{}, NewAPI(), "expects an instance of hyperdrive.API")
}

func (suite *HyperdriveTestSuite) TestAPIServer() {
suite.IsType(&http.Server{}, NewAPI().Server, "expects an instance of *http.Server")
}

func (suite *HyperdriveTestSuite) TestNewEndpoint() {
suite.IsType(&Endpoint{}, suite.Endpoint, "expects an instance of hyperdrive.Endpoint")
}
Expand Down