From ed2bdfb5108887936c8eb7f1fed56e3acb541929 Mon Sep 17 00:00:00 2001 From: deadprogram Date: Fri, 18 Apr 2014 15:45:42 -0700 Subject: [PATCH] Add basic auth support to api --- api.go | 17 +++++++++++++---- examples/hello_api_auth.go | 26 ++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) create mode 100644 examples/hello_api_auth.go diff --git a/api.go b/api.go index 14ebf1cd..26d44de3 100644 --- a/api.go +++ b/api.go @@ -3,16 +3,19 @@ package gobot import ( "encoding/json" "github.com/go-martini/martini" + "github.com/martini-contrib/auth" "io/ioutil" "net/http" "reflect" ) type api struct { - master *Master - server *martini.ClassicMartini - Host string - Port string + master *Master + server *martini.ClassicMartini + Host string + Port string + Username string + Password string } type jsonRobot struct { @@ -36,6 +39,12 @@ type jsonConnection struct { } var startApi = func(me *api) { + username := me.Username + if username != "" { + password := me.Password + me.server.Use(auth.Basic(username, password)) + } + port := me.Port if port == "" { port = "3000" diff --git a/examples/hello_api_auth.go b/examples/hello_api_auth.go new file mode 100644 index 00000000..5b0a3441 --- /dev/null +++ b/examples/hello_api_auth.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + "github.com/hybridgroup/gobot" +) + +func Hello(params map[string]interface{}) string { + name := params["name"].(string) + return fmt.Sprintf("hi %v", name) +} + +func main() { + master := gobot.GobotMaster() + api := gobot.Api(master) + api.Username = "gort" + api.Password = "klatuu" + + hello := new(gobot.Robot) + hello.Name = "hello" + hello.Commands = map[string]interface{}{"Hello": Hello} + + master.Robots = append(master.Robots, hello) + + master.Start() +}