api: modify Start() for more modular initialization, and add StartRaw() for completely custom API implementations

Signed-off-by: Ron Evans <ron@hybridgroup.com>
This commit is contained in:
Ron Evans 2018-08-15 23:17:57 +02:00
parent 355181843f
commit 2c8f9e8641
3 changed files with 62 additions and 2 deletions

View File

@ -102,6 +102,19 @@ func (a *API) AddHandler(f func(http.ResponseWriter, *http.Request)) {
// Start initializes the api by setting up c3pio routes and robeaux
func (a *API) Start() {
a.AddC3PIORoutes()
a.AddRobeauxRoutes()
a.start(a)
}
// StartRaw initializes the api without setting up any routes. Good for custom web interfaces.
func (a *API) StartRaw() {
a.start(a)
}
// AddC3PIORoutes adds all of the standard C3PIO routes to the API.
func (a *API) AddC3PIORoutes() {
mcpCommandRoute := "/api/commands/:command"
robotDeviceCommandRoute := "/api/robots/:robot/devices/:device/commands/:command"
robotCommandRoute := "/api/robots/:robot/commands/:command"
@ -123,7 +136,10 @@ func (a *API) Start() {
a.Get("/api/robots/:robot/connections", a.robotConnections)
a.Get("/api/robots/:robot/connections/:connection", a.robotConnection)
a.Get("/api/", a.mcp)
}
// AddRobeauxRoutes adds all of the robeaux web interface routes to the API.
func (a *API) AddRobeauxRoutes() {
a.Get("/", func(res http.ResponseWriter, req *http.Request) {
http.Redirect(res, req, "/index.html", http.StatusMovedPermanently)
})
@ -136,8 +152,6 @@ func (a *API) Start() {
a.Get("/css/:a/", a.robeaux)
a.Get("/css/:a/:b", a.robeaux)
a.Get("/partials/:a", a.robeaux)
a.start(a)
}
// robeaux returns handler for robeaux routes.

View File

@ -34,6 +34,21 @@ func initTestAPI() *API {
return a
}
func TestStartRaw(t *testing.T) {
log.SetOutput(NullReadWriteCloser{})
g := gobot.NewMaster()
a := NewAPI(g)
a.start = func(m *API) {}
a.Get("/", func(res http.ResponseWriter, req *http.Request) {})
a.StartRaw()
request, _ := http.NewRequest("GET", "/", nil)
response := httptest.NewRecorder()
a.ServeHTTP(response, request)
gobottest.Assert(t, response.Code, 200)
}
func TestRobeaux(t *testing.T) {
a := initTestAPI()
// html assets

View File

@ -0,0 +1,31 @@
// +build example
//
// Do not build by default.
package main
import (
"fmt"
"net/http"
"gobot.io/x/gobot"
"gobot.io/x/gobot/api"
)
func main() {
master := gobot.NewMaster()
a := api.NewAPI(master)
a.Get("/", func(res http.ResponseWriter, req *http.Request) {
res.Write([]byte("OK"))
})
a.Get("/api/hello", func(res http.ResponseWriter, req *http.Request) {
msg := fmt.Sprintf("This command is attached to the robot %v", master.Robot("hello").Name)
res.Write([]byte(msg))
})
a.StartRaw()
master.AddRobot(gobot.NewRobot("hello"))
master.Start()
}