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 Route() (rest.App, error) { return rest.MakeRouter( // 新增某个服务 rest.Post("/apps", restGuarder(handler.CreateAppsHandler)), // 获取所有服务的基本信息 rest.Get("/apps", restGuarder(handler.GetInfoAppsHandler)), // TODO 获取某一个服务的详细信息 rest.Get("/apps/*appId", restGuarder(handler.GetSingleAppsHandler)), // 删除某一个服务的所有实例 rest.Delete("/apps/*appId", restGuarder(handler.DeleteAppsHandler)), // 新增或者更新一批服务 rest.Post("/apps/updater", restGuarder(handler.CreateOrUpdateAppsHandler)), // 回滚一批服务 rest.Post("/apps/rollback", restGuarder(handler.RollbackAppsHandler)), // 新增一批组信息 rest.Post("/groups", restGuarder(handler.DeployGroupsHandler)), // 给新增容器获取一个IP rest.Get("/ipholder/*cId", restGuarder(handler.CreateIpForContainer)), // 给删除容器释放所占用的IP rest.Delete("/ipholder/*cId", restGuarder(handler.DeleteIpForContainer)), // 填写某个容器信息 rest.Post("/containers", restGuarder(handler.CreateContainerInfo)), // 更新容器状态 rest.Post("/containers/:cId/:cState", restGuarder(handler.UpdateStateContainerInfo)), // 软删除容器 rest.Delete("/containers/soft/*cId", restGuarder(handler.MaskContainerInfo)), ) }
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() { 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 (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 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 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 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() { 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, err := rest.MakeRouter( rest.Get("/countries", GetAllCountries), rest.Post("/countries", PostCountry), rest.Get("/countries/:code", GetCountry), rest.Delete("/countries/:code", DeleteCountry), ) if err != nil { log.Fatal(err) } api.SetApp(router) log.Fatal(http.ListenAndServe(":8080", api.MakeHandler())) }
func main() { init_db() api := rest.NewApi() api.Use(rest.DefaultDevStack...) router, err := rest.MakeRouter( rest.Get("/os", GetAllOS), rest.Post("/os", PostOS), rest.Get("/os/:Distribution", GetOS), rest.Delete("/os/:Distribution", DeleteOS), ) if err != nil { log.Fatal(err) } api.SetApp(router) log.Fatal(http.ListenAndServe(":8080", api.MakeHandler())) }
func main() { fmt.Println("****** Test for a product ******") api := rest.NewApi() api.Use(rest.DefaultDevStack...) router, err := rest.MakeRouter( rest.Get("/products", GetAllProducts), rest.Post("/products", PostProduct), rest.Get("/products/:id", GetProduct), rest.Delete("/products/:id", DeleteProduct), ) if err != nil { log.Fatal(err) } api.SetApp(router) log.Fatal(http.ListenAndServe(":8080", api.MakeHandler())) log.Println("Listening on port 8080 -> go to http://localhost:8080") }
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() { email := rest_email.Email{} api := rest.NewApi() api.Use(rest.DefaultDevStack...) router, err := rest.MakeRouter( rest.Get("/", email.GetServiceList), rest.Get("/email", email.GetEmailListAndContent), rest.Post("/email", email.SendEmailContent), rest.Delete("/email", email.DeleteEmail), ) if err != nil { log.Fatal(err) } api.SetApp(router) log.Printf("email api server start...") log.Fatal(http.ListenAndServe(":8080", 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())) }
// NewRouter return the configured routes for this API func NewRouter(jwtmiddleware *jwt.JWTMiddleware, session *r.Session) rest.App { trips := models.Trips{ Conn: session, } router, err := rest.MakeRouter( rest.Post("/login", jwtmiddleware.LoginHandler), rest.Get("/refresh_token", jwtmiddleware.RefreshHandler), rest.Get("/trips", trips.GetAllTrips), rest.Get("/trips/:id", trips.GetTrip), rest.Post("/trips", trips.PostTrip), rest.Patch("/trips/:id/updatePlaces", trips.UpdateTripPlaces), rest.Delete("/trips/:id/deletePlace/:place", trips.DeleteTripPlaces), ) if err != nil { log.Fatal(err) } return router }
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 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())) }
// 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 }
func main() { var port string flag.StringVar(&port, "port", "9999", "port to listen") flag.Parse() log.Println("Starting server on localhost:" + port) countries := Countries{ Store: map[string]*Country{}, } // JSON Web Tokens middleware jwtMW := &jwt.JWTMiddleware{ Key: []byte("secret key"), Realm: "jwt auth", Timeout: time.Hour, MaxRefresh: time.Hour * 24, Authenticator: func(userid string, passwd string) bool { return userid == userID && passwd == password }, } api := rest.NewApi() statusMW := &rest.StatusMiddleware{} // StatusMiddleware must be registered in api.Use() BEFORE rest.DefaultDevStack // because of an implicit dependency on RecorderMiddleware (request.ENV["STATUS_CODE"]) // and reverse call order of Middleware#MiddlewareFunc(). api.Use(statusMW) api.Use(rest.DefaultDevStack...) // we use the IfMiddleware to remove certain paths from needing authentication //api.Use(&rest.IfMiddleware{ // Condition: func(r *rest.Request) bool { // return r.URL.Path != "/login" // }, // IfTrue: jwtMW, //}) router, err := rest.MakeRouter( rest.Get("/", func(w rest.ResponseWriter, r *rest.Request) { if e := w.WriteJson(map[string]string{"Body": "Hello, World!"}); e != nil { log.Println(e) } }), rest.Get("/lookup/#host", func(w rest.ResponseWriter, r *rest.Request) { ip, e := net.LookupIP(r.PathParam("host")) if e != nil { rest.Error(w, e.Error(), http.StatusInternalServerError) return } if e := w.WriteJson(&ip); e != nil { log.Println(e) } }), rest.Get("/countries", countries.GetAllCountries), rest.Post("/countries", countries.PostCountry), rest.Get("/countries/:code", countries.GetCountry), rest.Delete("/countries/:code", countries.DeleteCountry), rest.Get("/stats", func(w rest.ResponseWriter, r *rest.Request) { returnJSON(w, statusMW.GetStatus()) }), rest.Post("/login", jwtMW.LoginHandler), rest.Get("/auth_test", handleAuth), rest.Get("/refresh_token", jwtMW.RefreshHandler), rest.Get("/stream", StreamThings), ) if err != nil { log.Fatal(err) } http.Handle("/api/", http.StripPrefix("/api", api.MakeHandler())) http.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir(".")))) api.SetApp(router) log.Fatal(http.ListenAndServe(":"+port, api.MakeHandler())) }
func main() { flag.Parse() p, err := osext.ExecutableFolder() if err != nil { log.Fatal(err) } dbconf, err := load(path.Join(p, "db", "config.json"), *flagEnv) if err != nil { log.Fatal(err) } // db, err := sql.Open(dbconf.Driver, dbconf.Source) db, err := hood.Open(dbconf.Driver, dbconf.Source) if err != nil { log.Fatal(err) } // svmw := semVerMiddleware{ // MinVersion: "1.0.0", // MaxVersion: "1.0.0", // } serviceApi := api.Api{Db: db} rapi := rest.NewApi() rapi.Use(rest.DefaultDevStack...) router, err := rest.MakeRouter( rest.Get("/tags", serviceApi.GetAllTags), rest.Post("/tags", serviceApi.PostTag), rest.Get("/tags/:name", serviceApi.GetTag), rest.Post("/tags/:name", serviceApi.UpdateTag), rest.Delete("/tags/:name", serviceApi.DeleteTag), rest.Get("/contacts", serviceApi.GetAllContacts), rest.Post("/contacts", serviceApi.PostContact), rest.Get("/contacts/:name", serviceApi.GetContact), rest.Post("/contacts/:name", serviceApi.UpdateContact), rest.Delete("/contacts/:name", serviceApi.DeleteContact), // rest.Get("/#version/message", svmw.MiddlewareFunc( // func(w rest.ResponseWriter, req *rest.Request) { // version := req.Env["VERSION"].(*semver.Version) // if version.Major == 2 { // // http://en.wikipedia.org/wiki/Second-system_effect // w.WriteJson(map[string]string{ // "Body": "Hello broken World!", // }) // } else { // w.WriteJson(map[string]string{ // "Body": "Hello World!", // }) // } // }, // )), ) if err != nil { log.Fatal(err) } rapi.SetApp(router) http.Handle("/api/", http.StripPrefix("/api", rapi.MakeHandler())) log.Println("Started") log.Fatal(http.ListenAndServe(":8080", nil)) }
// MakeHandler constructs and returns an HTTP handler for the API. Returns an // error if unsuccessful. func MakeHandler() (http.Handler, error) { api := rest.NewApi() api.Use(rest.DefaultDevStack...) router, err := rest.MakeRouter( // Auth rest.Get("/auth/#provider", BeginAuth), rest.Get("/auth/#provider/callback", CallbackAuth), rest.Post("/logout", Logout), // Channels rest.Get("/channels", GetChannels), rest.Get("/channels/#channelname", GetChannel), // rest.Put("/channels/#channelname", SetChannel), rest.Post("/channels", AddChannel), rest.Delete("/channels/#channelname", RemoveChannel), // Moderators rest.Get("/channels/#channelname/moderators", GetModerators), rest.Post("/channels/#channelname/moderators", AddModerator), rest.Delete("/channels/#channelname/moderators/#userID", RemoveModerator), // Viewers rest.Get("/channels/#channelname/viewers", GetViewers), rest.Post("/channels/#channelname/viewers", AddViewer), rest.Delete("/channels/#channelname/viewers/#userID", RemoveViewer), // Banned rest.Get("/channels/#channelname/bans", GetBans), rest.Post("/channels/#channelname/bans", AddBan), rest.Delete("/channels/#channelname/bans/#userID", RemoveBan), // Posts rest.Get("/posts", GetPosts), rest.Get("/posts/#pid", GetPost), // rest.Put("/posts/#pid", SetPost), rest.Post("/posts", AddPost), rest.Delete("/posts/#pid", RemovePost), // Comments rest.Get("/posts/#pid/comments", GetComments), // rest.Put("/posts/#pid/comments/#cid", SetComment), rest.Post("/posts/#pid/comments", AddComment), rest.Delete("/posts/#pid/comments/#cid", RemoveComment), // Users rest.Get("/users", GetUsers), rest.Get("/users/#userID", GetUser), rest.Post("/users/#userID", AddUser), rest.Delete("/users/#userID", RemoveUser), // Subscriptions rest.Get("/users/#userID/subscriptions", GetSubscriptions), rest.Post("/users/#userID/subscriptions", AddSubscription), rest.Delete("/users/#userID/subscriptions/#channelname", RemoveSubscription), // Favorites rest.Get("/users/#userID/favorites", GetFavorites), rest.Post("/users/#userID/favorites", AddFavorite), rest.Delete("/users/#userID/favorites/#postID", RemoveFavorite), ) if err != nil { return nil, err } api.SetApp(router) return api.MakeHandler(), nil }
func NewWebApi() http.Handler { Authenticator := func(userId, password string) bool { res, err := userRepository.GetUserById(userId) if err != nil || res == "" { return false } user := domain.NewUser() err = json.Unmarshal([]byte(res), user) return nil == err && user.Pass == domain.HashPassword(password) } var jwt_middleware = &jwt.JWTMiddleware{ Key: []byte("testKey"), Realm: "Unitrans", Timeout: time.Hour * 30, MaxRefresh: time.Hour * 24, Authenticator: Authenticator, } var DevStack = []rest.Middleware{ &rest.AccessLogApacheMiddleware{}, &rest.TimerMiddleware{}, &rest.RecorderMiddleware{}, &rest.PoweredByMiddleware{ XPoweredBy: "unitrans", }, &rest.RecoverMiddleware{ EnableResponseStackTrace: true, }, &rest.JsonIndentMiddleware{}, } api := rest.NewApi() api.Use(DevStack...) api.Use(&rest.CorsMiddleware{ RejectNonCorsRequests: false, OriginValidator: func(origin string, request *rest.Request) bool { return true }, AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"}, AllowedHeaders: []string{"Authorization", "Accept", "Content-Type", "X-Custom-Header", "Origin"}, AccessControlAllowCredentials: true, AccessControlMaxAge: 3600, }) api.Use(&rest.IfMiddleware{ Condition: func(request *rest.Request) bool { return request.URL.Path != "/login" && request.URL.Path != "/refresh" && request.URL.Path != "/register" && request.URL.Path != "/checkExists" && request.URL.Path != "/tr" }, IfTrue: jwt_middleware, }) api.Use(&rest.IfMiddleware{ Condition: func(r *rest.Request) bool { _, ok := r.Env["REMOTE_USER"] return ok }, IfTrue: &UserMiddleware{}, }) api_router, _ := rest.MakeRouter( rest.Post("/login", jwt_middleware.LoginHandler), rest.Get("/test", handle_auth), rest.Get("/refresh", jwt_middleware.RefreshHandler), rest.Post("/register", Register), rest.Post("/checkExists", CheckExists), rest.Get("/keys", KeysList), rest.Post("/keys", KeyCreate), rest.Delete("/keys/*key", KeyDelete), rest.Post("/tr", Translate), ) api.SetApp(api_router) return api.MakeHandler() }
func TestContactApi(t *testing.T) { // db, err := sql.Open(dbconf.Driver, dbconf.Source) db, err := hood.Open("postgres", "user=postgres dbname=indata_test host=192.168.0.10 sslmode=disable") if err != nil { log.Fatal(err) } serviceApi := api.Api{Db: db} rapi := rest.NewApi() rapi.Use(rest.DefaultDevStack...) router, err := rest.MakeRouter( rest.Get("/contacts", serviceApi.GetAllContacts), rest.Post("/contacts", serviceApi.PostContact), rest.Get("/contacts/:name", serviceApi.GetContact), rest.Post("/contacts/:name", serviceApi.UpdateContact), rest.Delete("/contacts/:name", serviceApi.DeleteContact), ) if err != nil { log.Fatal(err) } rapi.SetApp(router) // Start a transaction tx := db.Begin() tx.DropTableIfExists(api.Tag{}) tx.DropTableIfExists(api.Contact{}) tx.DropTableIfExists(api.TagContact{}) tx.CreateTableIfNotExists(api.Tag{}) tx.CreateTableIfNotExists(api.Contact{}) tx.CreateTableIfNotExists(api.TagContact{}) // Commit changes err = tx.Commit() if err != nil { log.Println(err) } handler := http.StripPrefix("/api", rapi.MakeHandler()) recorded := test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/api/contacts", nil)) recorded.CodeIs(200) recorded.ContentTypeIsJson() // recorded.ContentEncodingIsGzip() recorded.BodyIs(`[]`) recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("POST", "http://localhost/api/contacts", &map[string]string{ "name": "a", "title": "a", "description": "a", })) recorded.CodeIs(200) recorded.ContentTypeIsJson() // recorded.ContentEncodingIsGzip() recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/api/contacts", nil)) recorded.CodeIs(200) recorded.ContentTypeIsJson() // recorded.ContentEncodingIsGzip() var contacts []api.Contact err = recorded.DecodeJsonPayload(&contacts) if len(contacts) != 1 { t.Errorf(`Expected one element and got %d`, len(contacts)) } if contacts[0].Name != "a" { t.Error(`Expected contact name "a"`) } spew.Dump(contacts) recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("DELETE", "http://localhost/api/contacts/"+contacts[0].Name, nil)) recorded.CodeIs(200) recorded.ContentTypeIsJson() recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/api/contacts", nil)) recorded.CodeIs(200) recorded.ContentTypeIsJson() // recorded.ContentEncodingIsGzip() recorded.BodyIs(`[]`) }
// 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 }
func TestTagApi(t *testing.T) { tests := []TestTagStruct{ { First: &TestTag{ Request: "GET", Url: "http://localhost/api/tags", Status: 200, Body: `[]`, }, }, { First: &TestTag{ Request: "POST", Url: "http://localhost/api/tags", Input: &map[string]string{ "name": "a", }, Status: 200, }, Last: &TestTag{ Request: "GET", Url: "http://localhost/api/tags", Input: nil, Status: 200, Result: &api.Tag{ Name: "a", Weight: 20, }, }, }, } // db, err := sql.Open(dbconf.Driver, dbconf.Source) db, err := hood.Open("postgres", "user=postgres dbname=indata_test host=192.168.0.10 sslmode=disable") if err != nil { log.Fatal(err) } serviceApi := api.Api{Db: db} rapi := rest.NewApi() rapi.Use(rest.DefaultCommonStack...) // rapi.Use(&rest.AccessLogApacheMiddleware{}) // rapi.Use(&rest.GzipMiddleware{}) rapi.Use(&rest.ContentTypeCheckerMiddleware{}) router, err := rest.MakeRouter( rest.Get("/tags", serviceApi.GetAllTags), rest.Post("/tags", serviceApi.PostTag), rest.Get("/tags/:name", serviceApi.GetTag), rest.Post("/tags/:name", serviceApi.UpdateTag), rest.Delete("/tags/:name", serviceApi.DeleteTag), ) if err != nil { log.Fatal(err) } rapi.SetApp(router) for _, testVars := range tests { // Start a transaction tx := db.Begin() tx.DropTableIfExists(api.Tag{}) tx.DropTableIfExists(api.Contact{}) tx.DropTableIfExists(api.TagContact{}) tx.CreateTableIfNotExists(api.Tag{}) tx.CreateTableIfNotExists(api.Contact{}) tx.CreateTableIfNotExists(api.TagContact{}) // Commit changes err = tx.Commit() if err != nil { log.Println(err) } hndl := rapi.MakeHandler() handler := http.StripPrefix("/api", hndl) // recorded := test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/api/tags/notfound", nil)) // recorded.CodeIs(404) // recorded.ContentTypeIsJson() // recorded.BodyIs("{\n \"Error\": \"Resource not found\"\n}") // recorded = test.RunRequest(t, &handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/user-notfound", nil)) // recorded.CodeIs(404) // recorded.ContentTypeIsJson() // recorded.BodyIs(`{"Error":"Resource not found"}`) log.Printf("%s request to %s ", testVars.First.Request, testVars.First.Url) recorded := test.RunRequest(t, handler, test.MakeSimpleRequest(testVars.First.Request, testVars.First.Url, testVars.First.Input)) recorded.CodeIs(testVars.First.Status) recorded.ContentTypeIsJson() // recorded.ContentEncodingIsGzip() log.Printf("body %#v", recorded.Recorder.Body.String()) if testVars.First.Body != "" { recorded.BodyIs(testVars.First.Body) } if testVars.Last != nil { log.Printf("%s request to %s ", testVars.Last.Request, testVars.Last.Url) recorded := test.RunRequest(t, handler, test.MakeSimpleRequest(testVars.Last.Request, testVars.Last.Url, testVars.Last.Input)) recorded.CodeIs(testVars.Last.Status) recorded.ContentTypeIsJson() // recorded.ContentEncodingIsGzip() if testVars.Last.Result != nil { var tags []api.Tag err = recorded.DecodeJsonPayload(&tags) log.Printf("tags %#v", tags) if len(tags) != 1 { t.Errorf(`Expected one element and got %d`, len(tags)) } if testVars.Last.Result.Name != "" { if tags[0].Name != testVars.Last.Result.Name { t.Errorf(`Expected tag name "%s"`, testVars.Last.Result.Name) } } // if ok := testVars.Last.Result.Weight; ok { // if testVars.Last.Result.Weight { if tags[0].Weight != testVars.Last.Result.Weight { t.Errorf(`Expected tag weight "%s"`, testVars.Last.Result.Weight) } // } // } } } } // // recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/api/tags", nil)) // recorded.CodeIs(200) // recorded.ContentTypeIsJson() // // recorded.ContentEncodingIsGzip() // // var tags []api.Tag // err = recorded.DecodeJsonPayload(&tags) // // if len(tags) != 1 { // t.Errorf(`Expected one element and got %d`, len(tags)) // } // // if tags[0].Name != "a" { // t.Error(`Expected tag name "a"`) // } // // recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("DELETE", "http://localhost/api/tags/"+tags[0].Name, nil)) // recorded.CodeIs(200) // recorded.ContentTypeIsJson() // // recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/api/tags", nil)) // recorded.CodeIs(200) // recorded.ContentTypeIsJson() // // recorded.ContentEncodingIsGzip() // recorded.BodyIs(`[]`) }