func (fe *Frontend) RunServer(blocking bool) http.Handler { api := rest.NewApi() api.Use(&rest.AuthBasicMiddleware{ Realm: "test zone", Authenticator: func(userId string, password string) bool { if userId == fe.cfg.Network.Username && password == fe.cfg.Network.Password { return true } return false }, }) api.Use(rest.DefaultDevStack...) router, err := rest.MakeRouter( rest.Get("/subnets", fe.GetAllSubnets), rest.Get("/subnets/#id", fe.GetSubnet), rest.Post("/subnets", fe.CreateSubnet), rest.Put("/subnets/#id", fe.UpdateSubnet), rest.Delete("/subnets/#id", fe.DeleteSubnet), rest.Post("/subnets/#id/bind", fe.BindSubnet), rest.Delete("/subnets/#id/bind/#mac", fe.UnbindSubnet), rest.Put("/subnets/#id/next_server/#ip", fe.NextServer), ) if err != nil { log.Fatal(err) } api.SetApp(router) connStr := fmt.Sprintf(":%d", fe.cfg.Network.Port) log.Println("Web Interface Using", connStr) if blocking { if fe.cert_pem == "" || fe.key_pem == "" { log.Fatal(http.ListenAndServe(connStr, api.MakeHandler())) } else { log.Fatal(http.ListenAndServeTLS(connStr, fe.cert_pem, fe.key_pem, api.MakeHandler())) } } return api.MakeHandler() }
func initRoutes(restApi *rest.Api) { authController := &AuthController{} appController := &ApplicationController{} typesController := &TypesController{} router, err := rest.MakeRouter( rest.Put(authController.Path(), authController.RegisterUserHandler), rest.Post(authController.Path(), authController.LoginUserHandler), rest.Put("/:appId"+authController.Path(), authController.AppRegisterUserHandler), rest.Post("/:appId"+authController.Path(), authController.AppLoginUserHandler), rest.Post(appController.Path(), appController.CreateApplicationHandler), rest.Get(appController.Path(), appController.GetApplicationsHandler), rest.Get(appController.Path()+"/:appId", appController.GetApplicationHandler), rest.Delete(appController.Path()+"/:appId", appController.DeleteApplicationHandler), rest.Put(appController.Path()+"/:appId", appController.UpdateApplicationHandler), rest.Post("/:appId"+typesController.Path(), typesController.CreateTypeHandler), rest.Delete("/:appId"+typesController.Path()+"/:typeName", typesController.DeleteType), rest.Post("/:appId"+typesController.Path()+"/:typeName", typesController.InsertInTypeHandler), rest.Get("/:appId"+typesController.Path()+"/:typeName", typesController.GetTypeDataHandler), rest.Get("/:appId"+typesController.Path()+"/:typeName/:itemId", typesController.GetTypeItemById), rest.Put("/:appId"+typesController.Path()+"/:typeName/:itemId", typesController.UpdateTypeItemById), rest.Delete("/:appId"+typesController.Path()+"/:typeName/:itemId", typesController.DeleteTypeItemById), ) if err != nil { log.Fatal(err) } restApi.SetApp(router) }
func main() { api := rest.NewApi() statusMw := &rest.StatusMiddleware{} api.Use(statusMw) api.Use(&rest.GzipMiddleware{}) api.Use(&rest.AccessLogJsonMiddleware{}) api.Use(rest.DefaultDevStack...) router, err := rest.MakeRouter( //used for service status reporting rest.Get("/data/.status", func(w rest.ResponseWriter, r *rest.Request) { w.WriteJson(statusMw.GetStatus()) }), rest.Post("/login", login), rest.Post("/refresh", refresh), rest.Post("/signup", signup), rest.Get("/data/:userid/smbgs", func(w rest.ResponseWriter, r *rest.Request) { checkAuth(w, r, getSmbgs) }), rest.Post("/data/:userid/smbgs", func(w rest.ResponseWriter, r *rest.Request) { checkAuth(w, r, postSmbgs) }), rest.Put("/data/:userid/smbgs", notImplemented), rest.Get("/data/:userid/notes", func(w rest.ResponseWriter, r *rest.Request) { checkAuth(w, r, getNotes) }), rest.Post("/data/:userid/notes", func(w rest.ResponseWriter, r *rest.Request) { checkAuth(w, r, postNotes) }), rest.Put("/data/:userid/notes", notImplemented), rest.Get("/data/:userid/basals", notImplemented), rest.Post("/data/:userid/basals", notImplemented), rest.Put("/data/:userid/basals", notImplemented), rest.Get("/data/:userid/boluses", notImplemented), rest.Post("/data/:userid/boluses", notImplemented), rest.Put("/data/:userid/boluses", notImplemented), rest.Get("/data/:userid/cbgs", notImplemented), rest.Post("/data/:userid/cbgs", notImplemented), rest.Put("/data/:userid/cbgs", notImplemented), ) if err != nil { log.Fatal(err) } api.SetApp(router) log.Println(http.ListenAndServe(":8090", api.MakeHandler())) }
func main() { var err error api := rest.NewApi() // Enable basic middlewares. api.Use(rest.DefaultDevStack...) // Enable CORS middleware. api.Use(&rest.CorsMiddleware{ RejectNonCorsRequests: false, OriginValidator: func(origin string, request *rest.Request) bool { return true }, AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"}, AllowedHeaders: []string{ "Accept", "Content-Type", "X-Custom-Header", "Origin"}, AccessControlAllowCredentials: true, AccessControlMaxAge: 3600, }) // Enable token validation middleware. api.Use(&mw.AuthMW{}) router, err := rest.MakeRouter( // cards. rest.Get("/cards", GetUserCards), rest.Get("/cards/:cid", GetCard), rest.Post("/cards", CreateCard), rest.Put("/cards/:cid", UpdateCard), rest.Delete("/cards/:cid", DeleteCard), rest.Get("/challenge", GetChallenge), rest.Post("/results", SaveResult), // user endpoints. rest.Get("/users/:uid", GetUser), rest.Put("/users/:uid", UpdateUser), rest.Delete("/users/:uid", DeleteUser), // token rest.Post("/token", GetToken), // ping rest.Get("/ping", Ping), ) if err != nil { log.Fatal(err) } api.SetApp(router) log.Fatal(http.ListenAndServe(":8080", api.MakeHandler())) }
func main() { i := Impl{} i.InitDB() i.InitSchema() api := rest.NewApi() api.Use(rest.DefaultDevStack...) api.Use(&rest.CorsMiddleware{ RejectNonCorsRequests: false, OriginValidator: func(origin string, request *rest.Request) bool { return true }, AllowedMethods: []string{"GET", "POST", "PUT"}, AllowedHeaders: []string{ "Accept", "Content-Type", "X-Custom-Header", "Origin"}, AccessControlAllowCredentials: true, AccessControlMaxAge: 3600, }) router, err := rest.MakeRouter( rest.Get("/services", i.GetAllServices), rest.Post("/services", i.PostService), rest.Get("/services/:id", i.GetService), rest.Put("/services/:id", i.PutService), rest.Delete("/services/:id", i.DeleteService), ) if err != nil { log.Fatal(err) } api.SetApp(router) log.Fatal(http.ListenAndServe(":8080", api.MakeHandler())) }
func getRouter() (rest.App, error) { mcPlugins := routes.McPlugins{} router, err := rest.MakeRouter( rest.Get("/plugins", mcPlugins.GetAllPlugins), rest.Post("/plugins", mcPlugins.PostPlugin), rest.Get("/plugins/:id", mcPlugins.GetPlugin), rest.Put("/plugins/:id", mcPlugins.PutPlugin), rest.Delete("/plugins/:id", mcPlugins.DeletePlugin), ) return router, err }
func (r *restServerAPI) MakeHandler() (http.Handler, error) { router, err := grest.MakeRouter( // Auth grest.Post("/login", r.Login), // Users grest.Get("/me", r.Me), grest.Get("/users", r.ListUsers), grest.Get("/users/#email", r.GetUser), grest.Post("/users/#email", r.CreateUser), grest.Put("/users/#email", r.UpdateUser), // Groups grest.Get("/groups", r.ListGroups), grest.Get("/groups/#email", r.GetGroup), grest.Post("/groups/#email", r.CreateGroup), grest.Put("/groups/#email", r.UpdateGroup), ) if err != nil { return nil, err } r.rest.SetApp(router) return r.rest.MakeHandler(), nil }
func main() { // serve ng-admin angular app fs := http.FileServer(http.Dir("static")) http.Handle("/admin/", http.StripPrefix("/admin/", fs)) db, err := sql.Open("sqlite3", "./blog.db") defer db.Close() if err != nil { panic(err) } api := rest.NewApi() api.Use(rest.DefaultProdStack...) api.Use(&rest.CorsMiddleware{ RejectNonCorsRequests: false, OriginValidator: func(origin string, request *rest.Request) bool { return true }, AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"}, AllowedHeaders: []string{ "Accept", "Content-Type", "X-Total-Count", "Origin"}, AccessControlAllowCredentials: true, AccessControlMaxAge: 3600, }) // initialize Entity REST API entityManager := eram.NewEntityDbManager(db) entityRestApi := era.NewEntityRestAPI(entityManager) router, err := rest.MakeRouter( rest.Get("/api/:entity", entityRestApi.GetAllEntities), rest.Post("/api/:entity", entityRestApi.PostEntity), rest.Get("/api/:entity/:id", entityRestApi.GetEntity), rest.Put("/api/:entity/:id", entityRestApi.PutEntity), rest.Delete("/api/:entity/:id", entityRestApi.DeleteEntity), ) if err != nil { log.Fatal(err) } api.SetApp(router) http.Handle("/api/", api.MakeHandler()) log.Fatal(http.ListenAndServe(":8080", nil)) }
func main() { users := Users{ Store: map[string]*User{}, } books := Books{ Store: map[string]*Book{}, } api := rest.NewApi() api.Use(rest.DefaultDevStack...) router, err := rest.MakeRouter( // users router rest.Get("/users", users.GetAllUsers), rest.Post("/users", users.PostUser), rest.Get("/users/:id", users.GetUser), rest.Put("/users/:id", users.PutUser), rest.Delete("/users/:id", users.DeleteUser), // user and book router rest.Get("/users/:id/books", users.GetUserAllBooks), // books router rest.Get("/books", books.GetAllBooks), rest.Post("/books", books.PostBook), rest.Get("/books/:id", books.GetBook), rest.Put("/books/:id", books.PutBook), rest.Delete("/books/:id", books.DeleteBook), ) if err != nil { log.Fatal(err) } api.SetApp(router) log.Fatal(http.ListenAndServe(":8080", api.MakeHandler())) }
func main() { api := rest.NewApi() api.Use(rest.DefaultDevStack...) router, _ := rest.MakeRouter( rest.Post("/rest/c", postDataC), rest.Get("/rest/d", getDataD), rest.Put("/rest/e/msg/:host", putDataE), ) //TEST call to dataplus initData() //log.Printf("Started on 9090") api.SetApp(router) log.Fatal(http.ListenAndServe(":8080", api.MakeHandler())) }
func (r *Controller) serveREST(conf *goconf.ConfigFile) { c, err := parseRESTConfig(conf) if err != nil { r.log.Err(fmt.Sprintf("Controller: parsing REST configurations: %v", err)) return } api := rest.NewApi() router, err := rest.MakeRouter( rest.Get("/api/v1/switch", r.listSwitch), rest.Post("/api/v1/switch", r.addSwitch), rest.Delete("/api/v1/switch/:id", r.removeSwitch), rest.Options("/api/v1/switch/:id", r.allowOrigin), rest.Get("/api/v1/port/:switchID", r.listPort), rest.Get("/api/v1/network", r.listNetwork), rest.Post("/api/v1/network", r.addNetwork), rest.Delete("/api/v1/network/:id", r.removeNetwork), rest.Options("/api/v1/network/:id", r.allowOrigin), rest.Get("/api/v1/ip/:networkID", r.listIP), rest.Get("/api/v1/host", r.listHost), rest.Post("/api/v1/host", r.addHost), rest.Delete("/api/v1/host/:id", r.removeHost), rest.Options("/api/v1/host/:id", r.allowOrigin), rest.Get("/api/v1/vip", r.listVIP), rest.Post("/api/v1/vip", r.addVIP), rest.Delete("/api/v1/vip/:id", r.removeVIP), rest.Options("/api/v1/vip/:id", r.allowOrigin), rest.Put("/api/v1/vip/:id", r.toggleVIP), ) if err != nil { r.log.Err(fmt.Sprintf("Controller: making a REST router: %v", err)) return } api.SetApp(router) addr := fmt.Sprintf(":%v", c.port) if c.tls.enable { err = http.ListenAndServeTLS(addr, c.tls.certFile, c.tls.keyFile, api.MakeHandler()) } else { err = http.ListenAndServe(addr, api.MakeHandler()) } if err != nil { r.log.Err(fmt.Sprintf("Controller: listening on HTTP: %v", err)) return } }
func main() { // Static Files fs := http.FileServer(http.Dir("app/dist")) http.Handle("/", fs) log.Println("Listening...") go http.ListenAndServe(":8080", nil) // Api api := rest.NewApi() api.Use(rest.DefaultDevStack...) api.Use(&rest.CorsMiddleware{ RejectNonCorsRequests: false, OriginValidator: func(origin string, request *rest.Request) bool { return true // origin == "http://127.0.0.1" }, AllowedMethods: []string{"GET", "POST", "PUT", "OPTIONS", "DELETE"}, AllowedHeaders: []string{ "Accept", "Content-Type", "Authorization", "Origin"}, AccessControlAllowCredentials: true, AccessControlMaxAge: 3600, }) api.Use(AuthMiddleware()) router, err := rest.MakeRouter( rest.Post("/auth/login", restapi.Login), rest.Post("/auth/register", restapi.Register), rest.Post("/api/importurl", restapi.ImportUrl), rest.Get("/api/documents", restapi.GetAllDocuments), rest.Post("/api/documents", restapi.PostDocument), rest.Get("/api/documents/:id", restapi.GetDocument), rest.Put("/api/documents/:id", restapi.PutDocument), rest.Delete("/api/documents/:id", restapi.DeleteDocument), ) if err != nil { log.Fatal(err) } api.SetApp(router) log.Printf("Port %s\n", conf.Port) log.Fatal(http.ListenAndServe(":"+conf.Port, api.MakeHandler())) }
func main() { api := rest.NewApi() api.Use(rest.DefaultDevStack...) router, err := rest.MakeRouter( rest.Post("/api/v1/images", HandleImageCreate), rest.Get("/api/v1/images", HandleImageList), rest.Post("/api/v1/instances", HandleInstanceCreate), rest.Post("/api/v1/instances/:instanceid", HandleInstanceStart), rest.Put("/api/v1/instances/:instanceid", HandleInstanceStop), rest.Get("/api/v1/instances", HandleInstanceList), rest.Get("/api/v1/instances/:instanceid", HandleInstanceInfo), rest.Delete("/api/v1/instances/:instanceid", HandleInstanceDestroy), ) if err != nil { log.Fatal(err) } api.SetApp(router) log.Fatal(http.ListenAndServe(listen, api.MakeHandler())) }
func main() { i := Impl{} i.InitDB() i.InitSchema() api := rest.NewApi() api.Use(rest.DefaultDevStack...) router, err := rest.MakeRouter( rest.Get("/reminders", i.GetAllReminders), rest.Post("/reminders", i.PostReminder), rest.Get("/reminders/:id", i.GetReminder), rest.Put("/reminders/:id", i.PutReminder), rest.Delete("/reminders/:id", i.DeleteReminder), ) if err != nil { log.Fatal(err) } api.SetApp(router) log.Fatal(http.ListenAndServe(":8080", api.MakeHandler())) }
func (restapi *CyberBullyingEntryPointRestApiImpl) RegisterApi() { if restapi.Api == nil { restapi.SetApi(nil) } router, err := rest.MakeRouter( rest.Post("/api/signup", restapi.SignUpUser), rest.Post("/api/signin", restapi.SignUpUser), rest.Get("/api/#parentid/childinfo", restapi.GetChildInfo), rest.Post("/api/#parentid/childinfo", restapi.AddChildInfo), rest.Put("/api/#parentid/childinfo", restapi.UpdateChildInfo), rest.Get("/api/childbullydata/#parentid/#childid", restapi.GetChildBullyData), rest.Post("/api/childbullydata/#parentid/#childid", restapi.PostChildBullyData), rest.Post("/api/predict", restapi.PredictBullyData), ) if err != nil { restapi.LoggerImplPtr.Error(err.Error()) panic(err) } restapi.Api.SetApp(router) }
func GetRouter() (rest.App, error) { return rest.MakeRouter( // GET / // reponse : { version: "1.0" } rest.Get("/", func(res rest.ResponseWriter, req *rest.Request) { res.WriteJson(map[string]string{"version": "1.0"}) }), // PUT /index/#content-type/store // { // id: "4242", // terms: ["simple", "example"], // label: "It's just a simple example", // payload: { // foo: "bar" // } // score: 3 // OPTIONAL, default=1 (int) // } // // Add a new entry in redis // - id: can use few time the same ID to increment the score, but terms, // label and payload are stored only at first call rest.Put("/index/#content-type/store", IndexStore), // GET /index/#content-type/search?seed=examp&score=true&pretty=true&payload=true&ordered=true // -> Get a list of entries that match with the 'seed' parameter (multi-term matching) // - ?seed= : terms to match with // - ?ordered= (default true): return a list ordered by score // - ?score= (default false): return score (cf /index/#content-type/store) // - ?pretty= (default false): add <strong>exampl</strong> in the label // - ?payload= (default false): return the payload in the response rest.Get("/index/#content-type/search", Search), // GET /index/#content-type/#id // -> Get an object by ID // - ?payload= (default true): return the payload in the response rest.Get("/index/#content-type/#id", GetObject), ) }
func main() { api := rest.NewApi() api.Use(rest.DefaultDevStack...) router, err := rest.MakeRouter( // TODO http://docs.aws.amazon.com/AWSEC2/latest/APIReference/OperationList-query.html rest.Post("/api/v1/images", ImageCreate), rest.Get("/api/v1/images", ImageList), rest.Post("/api/v1/instances", InstanceCreate), rest.Post("/api/v1/instances/:instanceid", InstanceStart), rest.Put("/api/v1/instances/:instanceid", InstanceStop), rest.Get("/api/v1/instances", InstanceList), rest.Delete("/api/v1/instances/:instanceid", InstanceDestroy), ) if err != nil { log.Fatal(err) } api.SetApp(router) log.Fatal(http.ListenAndServe(listen, api.MakeHandler())) }
func init() { db, err := sql.Open("sqlite3", ":memory:") if err != nil { log.Fatal("An error '%s' was not expected when opening a stub database connection", err) } else { dat, err := ioutil.ReadFile("./../test.sql") if err != nil { log.Fatal("An error '%s' was not expected when opening sql file", err) } else { db.Exec(string(dat)) } } api := rest.NewApi() api.Use(rest.DefaultDevStack...) entityManager := eram.NewEntityDbManager(db) entityRestApi := NewEntityRestAPI(entityManager) router, err := rest.MakeRouter( rest.Get("/api/:entity", entityRestApi.GetAllEntities), rest.Post("/api/:entity", entityRestApi.PostEntity), rest.Get("/api/:entity/:id", entityRestApi.GetEntity), rest.Put("/api/:entity/:id", entityRestApi.PutEntity), rest.Delete("/api/:entity/:id", entityRestApi.DeleteEntity), ) if err != nil { log.Fatal("An error '%s' was not expected when creating the router", err) } api.SetApp(router) handler = api.MakeHandler() server = httptest.NewServer(handler) }
func NewApi() *ApiHander { handler := ApiHandler{ Api: rest.NewApi(), } handler.Api.Use(rest.DefaultDevStack...) router, err := rest.MakeRouter( rest.Post("/jobs", handler.CreateJob), rest.Get("/jobs", handler.GetJobs), rest.Get("/jobs/:id", handler.GetJob), rest.Put("/jobs/:id", handler.UpdateJob), rest.Delete("/jobs/:id", handler.DeleteJob), rest.Post("/procs", handler.StartProc), rest.Get("/procs/:id", handler.GetProc), rest.Delete("/procs/:id", handler.StopProc), rest.Get("/jobs/:id/procs", handler.GetProcsByJob), rest.Get("/jobs/:id/log", handler.GetProcLogByJob), ) if err != nil { log.Fatal(err) } handler.Api.SetApp(router) return &handler }
func main() { // db, err := gorm.Open("postgres", "user=gorm dbname=gorm sslmode=disable") // db, err := gorm.Open("foundation", "dbname=gorm") // FoundationDB. // db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local") db, err := gorm.Open("sqlite3", "../overlay.db") if err != nil { fmt.Println(err) } // You can also use an existing database connection handle // dbSql, _ := sql.Open("postgres", "user=gorm dbname=gorm sslmode=disable") // db, _ := gorm.Open("postgres", dbSql) // Get database connection handle [*sql.DB](http://golang.org/pkg/database/sql/#DB) db.DB() // Then you could invoke `*sql.DB`'s functions with it db.DB().Ping() db.DB().SetMaxIdleConns(10) db.DB().SetMaxOpenConns(100) // Disable table name's pluralization db.SingularTable(true) // Create table (won't recreate if it exists) db.CreateTable(&Overlay{}) // Drop table // db.DropTable(&User{}) // Automating Migration db.AutoMigrate(&Overlay{}) // db.AutoMigrate(&User{}, &Product{}, &Order{}) // Feel free to change your struct, AutoMigrate will keep your database up-to-date. // AutoMigrate will ONLY add *new columns* and *new indexes*, // WON'T update current column's type or delete unused columns, to protect your data. // If the table is not existing, AutoMigrate will create the table automatically. // o should be a pointer to an overlay struct // o := Overlay{ // KeyId: "lg_dev/PER01/00043", // VendorMode: "lg_dev", // Type: "p", // Description: "", // Grp: "PER01", // EId: "00041", // AppID: "NBC", // AlertPicUrl: "http://testurl.google.com", // Freshness: 86400, // NaggingEvent: 1, // DateEntered: time.Now(), // ExpireDate: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC), // CreateUser: "******", // ContentId: "TEST-001-SE09-EP11", // Series: "Big Bang Theory", // Season: 9, // Episode: 11, // Channel: "WFOX", // Vendor: "LG", // } i := Impl{} i.InitDB() i.InitSchema() api := rest.NewApi() api.Use(rest.DefaultDevStack...) router, err := rest.MakeRouter( rest.Get("/overlays", i.GetAllOverlays), rest.Post("/overlays", i.PostOverlay), rest.Get("/overlays/:id", i.GetOverlay), rest.Put("/overlays/:id", i.PutOverlay), rest.Delete("/overlays/:id", i.DeleteOverlay), ) if err != nil { log.Fatal(err) } api.SetApp(router) log.Fatal(http.ListenAndServe(":8080", api.MakeHandler())) }
// Start the webserver (non-blocking) func (ws *Webserver) Start() { go func() { defer func() { if r := recover(); r != nil { ws.panicChan <- r } }() api := rest.NewApi() api.Use(rest.DefaultDevStack...) router, err := rest.MakeRouter( rest.Get("/points", func(w rest.ResponseWriter, req *rest.Request) { if _, ok := ws.pilot.(pilotable); !ok { log.Error("WS is not initialized") rest.Error(w, "WS is not initialized", http.StatusInternalServerError) return } w.WriteJson(ws.tracer.GetPoints()) }), rest.Get("/autopilot", func(w rest.ResponseWriter, req *rest.Request) { if _, ok := ws.pilot.(pilotable); !ok { log.Error("WS is not initialized") rest.Error(w, "WS is not initialized", http.StatusInternalServerError) return } pi := ws.pilot.GetInfoAction() w.WriteJson(Autopilot{ Enabled: pi.Enabled, HeadingOffset: pi.HeadingOffset, SetPoint: pi.SetPoint, Course: pi.Course, Speed: pi.Speed, }) return }), rest.Get("/dashboard", func(w rest.ResponseWriter, req *rest.Request) { if _, ok := ws.dashboard.(queryable); !ok { log.Error("WS is not initialized") rest.Error(w, "WS is not initialized", http.StatusInternalServerError) return } data := ws.dashboard.GetDashboardInfoAction() w.WriteJson(data) }), rest.Put("/autopilot", func(w rest.ResponseWriter, r *rest.Request) { if _, ok := ws.pilot.(pilotable); !ok { log.Error("WS is not initialized") rest.Error(w, "WS is not initialized", http.StatusInternalServerError) return } autopilot := Control{} err := r.DecodeJsonPayload(&autopilot) if err != nil { log.Error("Failed to parse json:", err) rest.Error(w, err.Error(), http.StatusInternalServerError) return } log.Info("Got %v", autopilot) ws.pilot.SetOffset(autopilot.HeadingOffset) if autopilot.Enabled { err = ws.pilot.Enable() if err != nil { log.Error("Failed to enable autopilot:", err) rest.Error(w, err.Error(), http.StatusInternalServerError) return } } else { err = ws.pilot.Disable() if err != nil { log.Error("Failed to disable autopilot:", err) rest.Error(w, err.Error(), http.StatusInternalServerError) return } } w.WriteJson(map[string]string{"status": "OK"}) }), ) if err != nil { log.Panic(err) } api.SetApp(router) http.Handle("/api/", http.StripPrefix("/api", api.MakeHandler())) http.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir(".")))) http.HandleFunc("/version", VersionEndpoint(ws.version)) http.HandleFunc("/", redirect) err = http.ListenAndServe(":8000", nil) if err != nil { log.Panic("Already running! or there is something else alive on port 8000 - exiting") } }() }
// New creates a new instance of the Rest API. func New(s *store.Store, adminPassword string) (*rest.Api, error) { db := s.DB() models.NewBase(db).EnsureIndex() db.Session.Close() api := rest.NewApi() api.Use(rest.DefaultDevStack...) api.Use(&BaseMiddleware{ Store: s, }) api.Use(&rest.JsonpMiddleware{ CallbackNameKey: "cb", }) api.Use(&rest.CorsMiddleware{ RejectNonCorsRequests: false, OriginValidator: func(origin string, request *rest.Request) bool { return true }, AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, AllowedHeaders: []string{"Accept", "Content-Type", "Origin", "Authorization"}, AccessControlAllowCredentials: true, AccessControlMaxAge: 3600, }) authBasic := &AuthBasicMiddleware{ Realm: "Hooky", Authenticator: authenticate(adminPassword), Authorizator: authorize(adminPassword), } api.Use(&rest.IfMiddleware{ Condition: func(r *rest.Request) bool { return r.URL.Path != "/status" }, IfTrue: authBasic, }) router, err := rest.MakeRouter( rest.Get("/authenticate", Authenticate), rest.Post("/accounts", PostAccount), rest.Get("/accounts", GetAccounts), rest.Get("/accounts/:account", GetAccount), rest.Patch("/accounts/:account", PatchAccount), rest.Delete("/accounts/:account", DeleteAccount), rest.Delete("/accounts/:account/applications", DeleteApplications), rest.Get("/accounts/:account/applications", GetApplications), rest.Get("/accounts/:account/applications/:application", GetApplication), rest.Put("/accounts/:account/applications/:application", PutApplication), rest.Delete("/accounts/:account/applications/:application", DeleteApplication), rest.Get("/accounts/:account/applications/:application/queues", GetQueues), rest.Put("/accounts/:account/applications/:application/queues/:queue", PutQueue), rest.Delete("/accounts/:account/applications/:application/queues/:queue", DeleteQueue), rest.Get("/accounts/:account/applications/:application/queues/:queue", GetQueue), rest.Delete("/accounts/:account/applications/:application/queues", DeleteQueues), rest.Post("/accounts/:account/applications/:application/tasks", PutTask), rest.Get("/accounts/:account/applications/:application/tasks", GetTasks), rest.Delete("/accounts/:account/applications/:application/tasks", DeleteTasks), rest.Put("/accounts/:account/applications/:application/tasks/:task", PutTask), rest.Get("/accounts/:account/applications/:application/tasks/:task", GetTask), rest.Delete("/accounts/:account/applications/:application/tasks/:task", DeleteTask), rest.Post("/accounts/:account/applications/:application/tasks/:task/attempts", PostAttempt), rest.Get("/accounts/:account/applications/:application/tasks/:task/attempts", GetAttempts), rest.Get("/status", GetStatus), ) if err != nil { return nil, err } api.SetApp(router) return api, nil }
// New creates a new instance of the Rest API. func New(s *store.Store, adminPassword string, logStyle string) (*rest.Api, error) { api := rest.NewApi() if logStyle == "json" { api.Use(&rest.AccessLogJsonMiddleware{}) } else if strings.HasPrefix(logStyle, "apache-") { mw := &rest.AccessLogApacheMiddleware{} mw.Format = rest.DefaultLogFormat if logStyle == "apache-common" { mw.Format = rest.CommonLogFormat } else if logStyle == "apache-combined" { mw.Format = rest.CombinedLogFormat } api.Use(mw) } api.Use(rest.DefaultCommonStack...) api.Use(&BaseMiddleware{ Store: s, }) api.Use(&rest.JsonpMiddleware{ CallbackNameKey: "cb", }) api.Use(&rest.CorsMiddleware{ RejectNonCorsRequests: false, OriginValidator: func(origin string, request *rest.Request) bool { return true }, AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"}, AllowedHeaders: []string{"Accept", "Content-Type", "Origin", "Authorization"}, AccessControlAllowCredentials: true, AccessControlMaxAge: 3600, }) authBasic := &AuthBasicMiddleware{ Realm: "Hooky", Authenticator: authenticate(adminPassword), Authorizator: authorize(adminPassword), } api.Use(&rest.IfMiddleware{ Condition: func(r *rest.Request) bool { return r.URL.Path != "/status" }, IfTrue: authBasic, }) router, err := rest.MakeRouter( rest.Get("/authenticate", Authenticate), rest.Post("/accounts", PostAccount), rest.Get("/accounts", GetAccounts), rest.Get("/accounts/:account", GetAccount), rest.Patch("/accounts/:account", PatchAccount), rest.Delete("/accounts/:account", DeleteAccount), rest.Delete("/accounts/:account/applications", DeleteApplications), rest.Get("/accounts/:account/applications", GetApplications), rest.Get("/accounts/:account/applications/:application", GetApplication), rest.Put("/accounts/:account/applications/:application", PutApplication), rest.Delete("/accounts/:account/applications/:application", DeleteApplication), rest.Get("/accounts/:account/applications/:application/queues", GetQueues), rest.Put("/accounts/:account/applications/:application/queues/:queue", PutQueue), rest.Delete("/accounts/:account/applications/:application/queues/:queue", DeleteQueue), rest.Get("/accounts/:account/applications/:application/queues/:queue", GetQueue), rest.Delete("/accounts/:account/applications/:application/queues", DeleteQueues), rest.Post("/accounts/:account/applications/:application/tasks", PutTask), rest.Get("/accounts/:account/applications/:application/tasks", GetTasks), rest.Delete("/accounts/:account/applications/:application/tasks", DeleteTasks), rest.Put("/accounts/:account/applications/:application/tasks/:task", PutTask), rest.Get("/accounts/:account/applications/:application/tasks/:task", GetTask), rest.Delete("/accounts/:account/applications/:application/tasks/:task", DeleteTask), rest.Post("/accounts/:account/applications/:application/tasks/:task/attempts", PostAttempt), rest.Get("/accounts/:account/applications/:application/tasks/:task/attempts", GetAttempts), rest.Get("/accounts/:account/applications/:application/tasks/:task/attempts/:attempt", GetAttempt), rest.Get("/status", GetStatus), ) if err != nil { return nil, err } api.SetApp(router) return api, nil }