func main() {
	api := rest.NewApi()
	statusMw := &rest.StatusMiddleware{}
	api.Use(statusMw)
	api.Use(rest.DefaultDevStack...)
	auth := &rest.AuthBasicMiddleware{
		Realm: "test zone",
		Authenticator: func(userId string, password string) bool {
			if userId == "admin" && password == "admin" {
				return true
			}
			return false
		},
	}
	router, err := rest.MakeRouter(
		rest.Get("/countries", GetAllCountries),
		rest.Get("/.status", auth.MiddlewareFunc(
			func(w rest.ResponseWriter, r *rest.Request) {
				w.WriteJson(statusMw.GetStatus())
			},
		)),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
}
Exemple #2
0
func (s *server) StartServer() error {
	api := rest.NewApi()

	router, err := rest.MakeRouter(
		// system
		&rest.Route{"GET", "/v1/ping", s.ping},
		&rest.Route{"GET", "/v1/version", s.version},

		// v1
		&rest.Route{"GET", "/v1/secrets/:type/:name", s.serveSecret},
	)

	if err != nil {
		return err
	}

	api.SetApp(router)

	go func() {
		s.builder.Conf.Logger.Infof("Starting API on %d", s.builder.Conf.ApiPort)

		// 192.168.99.1
		if err := http.ListenAndServe(fmt.Sprintf("%s:%d", s.builder.Conf.ApiBinding, s.builder.Conf.ApiPort), api.MakeHandler()); err != nil {
			s.builder.Conf.Logger.Errorf("Failed to start API %s", err.Error())
			os.Exit(2)
		}

	}()

	return nil
}
Exemple #3
0
func main() {
	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	router, err := rest.MakeRouter(
		rest.Get("/weather/#location", func(w rest.ResponseWriter, req *rest.Request) {
			weather, err := GetWeather(req.PathParam("location"))
			if err != nil {
				rest.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			//w.WriteJson(&weather)
			//
			w.WriteJson(
				&WeatherResponse{
					Location:    fmt.Sprintf("%s", weather.CityName),
					Temperature: KelvinToFarenheit(weather.Main.Temp),
				},
			)
		}),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
}
Exemple #4
0
func main() {
	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.Post("/test", test),
	)

	// 存在しないルート時
	if err != nil {
		log.Fatal(err)
	}

	api.SetApp(router)
	log.Fatal(http.ListenAndServe(":9999", api.MakeHandler()))
}
Exemple #5
0
func MsgServerStart() {

	mqmsg := msgqueue.MqMsg{
		Msg: message.NewMsg(),
	}
	persistent := PerMqAgent{
		Msg: message.NewMsg(),
	}

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)

	router, err := rest.MakeRouter(
		//rest.Get("/test", msg.TestMsg),
		rest.Get("/testmq/:mqid", msgqueue.DefaultMM.TestMq),
		rest.Post("/send_msg/:mqid", mqmsg.PostMsg),
		rest.Get("/receive_msg/:mqid", mqmsg.GetMsg),
		rest.Post("/send/:mqid", persistent.PostMsg),
		rest.Get("/receive/:mqid", persistent.GetMsg),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	log.Fatal(http.ListenAndServe(":"+ListenPort, api.MakeHandler()))
}
Exemple #6
0
// NewRest configures REST api handlers and wrappers.
func NewRest() *rest.Api {
	api := rest.NewApi()
	api.MakeHandler()
	api.Use(rest.DefaultDevStack...)

	api.Use(&rest.CorsMiddleware{
		RejectNonCorsRequests: false,
		OriginValidator: func(origin string, request *rest.Request) bool {
			return true
		},
		AllowedMethods: []string{"GET", "POST"},
		AllowedHeaders: []string{
			"Accept", "Content-Type", "X-Custom-Header", "Origin"},
		AccessControlAllowCredentials: true,
		AccessControlMaxAge:           3600,
	})

	router, err := rest.MakeRouter(
		rest.Post("/translations", translations),
		rest.Post("/suggestions", suggestions),
		rest.Get("/health", health),
	)
	if err != nil {
		log.Fatal(err)
	}

	api.SetApp(router)
	return api
}
Exemple #7
0
/*
Microservice for accessing data
*/
func main() {
	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	api.Use(
		&rest.AuthBasicMiddleware{
			Realm:         "Smart Alarm Clock REST API",
			Authenticator: auth.AuthenticateByFile,
			Authorizator:  auth.AuthorizeRequest})
	router, err := rest.MakeRouter(
		rest.Get("/test/:time", view.GetJSONMessage),
		rest.Get("/calendar/next/:id", view.GetNextCalendarEntry),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	apilog.Init()
	calcom.InitApis()
	log.Fatal(
		http.ListenAndServeTLS(":1443",
			"/etc/sac/keys/cert.pem",
			"/etc/sac/keys/key.pem",
			api.MakeHandler(),
		),
	)
}
func main() {
	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	router, err := rest.MakeRouter(
		rest.Get("/message", func(w rest.ResponseWriter, req *rest.Request) {
			for cpt := 1; cpt <= 10; cpt++ {

				// wait 1 second
				time.Sleep(time.Duration(1) * time.Second)

				w.WriteJson(map[string]string{
					"Message": fmt.Sprintf("%d seconds", cpt),
				})
				w.(http.ResponseWriter).Write([]byte("\n"))

				// Flush the buffer to client
				w.(http.Flusher).Flush()
			}
		}),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)

	server := &graceful.Server{
		Timeout: 10 * time.Second,
		Server: &http.Server{
			Addr:    ":8080",
			Handler: api.MakeHandler(),
		},
	}

	log.Fatal(server.ListenAndServe())
}
Exemple #9
0
func main() {
	// context
	ctx = context.Background()

	// db
	hoge.BuildInstances()

	// redis
	redis_pool := newPool()
	ctx = context.WithValue(ctx, "redis", redis_pool)

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	router, err := rest.MakeRouter(
		rest.Post("/test", baseHandlerFunc(controller.Test)),
	)

	// 存在しないルート時
	if err != nil {
		log.Fatal(err)
	}

	api.SetApp(router)
	httpErr := http.ListenAndServe(":9999", api.MakeHandler())
	if httpErr != nil {
		log.Fatal(err, "http error!!")
	}
}
Exemple #10
0
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)
}
Exemple #11
0
func main() {
	// context
	ctx = context.Background()
	db := initDb()
	ctx = context.WithValue(ctx, "test", "aaabbbccc")
	ctx = context.WithValue(ctx, "DB", db)

	// redis
	redis_pool := newPool()
	ctx = context.WithValue(ctx, "redis", redis_pool)

	str := ctx.Value("test")
	log.Println(str)

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	router, err := rest.MakeRouter(
		rest.Post("/test", baseHandlerFunc(controller.Test)),
	)

	// 存在しないルート時
	if err != nil {
		log.Fatal(err)
	}

	api.SetApp(router)
	log.Fatal(http.ListenAndServe(":9999", api.MakeHandler()))
}
func (app *App) StartServer(addr string, dbFileName string) {
	err := app.InitDB(dbFileName)
	if err != nil {
		log.Fatal(err)
	}
	api := rest.NewApi()
	api.Use(rest.DefaultProdStack...)
	api.Use(&rest.CorsMiddleware{
		RejectNonCorsRequests: false,
		AllowedMethods:        []string{"GET", "POST"},
		AllowedHeaders: []string{
			"Accept", "Content-Type", "Origin"},
		AccessControlAllowCredentials: true,
		AccessControlMaxAge:           2592000,

		OriginValidator: func(origin string, request *rest.Request) bool {
			return true
		},
	})
	router, err := rest.MakeRouter(
		rest.Get("/latest", app.GetLatest),
		rest.Get("/last", app.GetLast),
		rest.Get("/all", app.GetAll),
		rest.Post("/postEntry", app.PostEntry),
		//rest.Post("/postSignedEntry", app.PostJwtEntry),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	log.Fatal(http.ListenAndServe(addr, api.MakeHandler()))
}
func main() {

	logit.Info.Println("cpmcontainerapi: containeragent starting")

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	router, err := rest.MakeRouter(
		&rest.Route{"GET", "/status", cpmcontainerapi.Status},
		&rest.Route{"POST", "/remotewritefile", cpmcontainerapi.RemoteWritefile},
		&rest.Route{"POST", "/seed", cpmcontainerapi.Seed},
		&rest.Route{"POST", "/startpg", cpmcontainerapi.StartPG},
		&rest.Route{"POST", "/stoppg", cpmcontainerapi.StopPG},
		&rest.Route{"POST", "/startpgonstandby", cpmcontainerapi.StartPGOnStandby},
		&rest.Route{"POST", "/initdb", cpmcontainerapi.Initdb},
		&rest.Route{"POST", "/startpgpool", cpmcontainerapi.StartPgpool},
		&rest.Route{"POST", "/stoppgpool", cpmcontainerapi.StopPgpool},
		&rest.Route{"POST", "/basebackup", cpmcontainerapi.Basebackup},
		&rest.Route{"POST", "/failover", cpmcontainerapi.Failover},
		&rest.Route{"POST", "/controldata", cpmcontainerapi.Controldata},
		&rest.Route{"POST", "/badgergenerate", cpmcontainerapi.BadgerGenerate},
		&rest.Route{"POST", "/restore", cpmcontainerapi.Restore},
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)

	http.Handle("/api/", http.StripPrefix("/api", api.MakeHandler()))
	http.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir("/pgdata/pg_log"))))

	log.Fatal(http.ListenAndServe(":10001", nil))
	log.Fatal(http.ListenAndServeTLS(":10000", "/var/cpm/keys/cert.pem", "/var/cpm/keys/key.pem", nil))
}
Exemple #14
0
func MakeApi() http.Handler {
	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)

	jwtMiddleware := &jwt.JWTMiddleware{
		Key:           []byte("super secret key"),
		Realm:         "Spacebook",
		Timeout:       time.Hour,
		MaxRefresh:    time.Hour * 24,
		Authenticator: authUser,
	}

	api.Use(&rest.IfMiddleware{
		Condition: func(request *rest.Request) bool {
			return request.URL.Path == "/pasteswithuser"
		},
		IfTrue: jwtMiddleware,
	})

	router, err := rest.MakeRouter(
		&rest.Route{"GET", "/pastes/:id", GetPaste},
		&rest.Route{"POST", "/pastes", PostPaste},
		&rest.Route{"POST", "/pasteswithuser", PostPasteWithUser},
		&rest.Route{"GET", "/pastes", GetAll},
		&rest.Route{"POST", "/login", jwtMiddleware.LoginHandler},
	)

	if err != nil {
		log.Fatal(err)
	}

	api.SetApp(router)
	return api.MakeHandler()
}
Exemple #15
0
func main() {

	servePort := os.Getenv(servePortEnv)

	if servePort == "" {
		servePort = defaultServePort
	}

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)

	router, err := rest.MakeRouter(
		rest.Get("/rnd", genRndNumber),
	)

	if err != nil {
		log.Fatal(err)
	}

	api.SetApp(router)
	bindPort := fmt.Sprintf(":%s", servePort)

	log.Printf("server listening on %s", bindPort)

	log.Fatal(http.ListenAndServe(bindPort, api.MakeHandler()))
}
Exemple #16
0
func main() {
	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	//配置API跨域CORS
	api.Use(&rest.CorsMiddleware{
		RejectNonCorsRequests: false,
		OriginValidator: func(origin string, req *rest.Request) bool {
			return origin == req.Header.Get("Origin")
		},
		AllowedMethods: []string{"GET", "POST", "PUT"},
		AllowedHeaders: []string{
			"Accept", "Content-Type", "X-Custom-Header", "Origin"},
		AccessControlAllowCredentials: true,
		AccessControlMaxAge:           3600,
	})

	//设置API基本Router
	router, err := rest.MakeRouter(
		rest.Post("/:raw.json", RawWrite),
		rest.Post("/auth/login/:id", AuthLogin),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
}
func main() {

	//fmt.Fprintln(os.Stderr, "this is an error message to stderr using Fprintln")
	logit.Info.Println("sleeping during startup to give DNS a chance")

	sleepTime, _ := time.ParseDuration("7s")
	time.Sleep(sleepTime)

	task.LoadSchedules()

	logit.Info.Println("taskserver starting")

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	router, err := rest.MakeRouter(
		&rest.Route{"POST", "/status/add", task.StatusAdd},
		&rest.Route{"POST", "/status/update", task.StatusUpdate},
		&rest.Route{"POST", "/executenow", task.ExecuteNow},
		&rest.Route{"POST", "/reload", task.Reload},
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)

	http.Handle("/api/", http.StripPrefix("/api", api.MakeHandler()))

	log.Fatal(http.ListenAndServe(":13001", nil))

}
func main() {

	logit.Info.Println("serveragent starting")

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	router, err := rest.MakeRouter(
		&rest.Route{"POST", "/metrics/iostat", cpmserverapi.MetricIostat},
		&rest.Route{"POST", "/metrics/df", cpmserverapi.MetricDf},
		&rest.Route{"POST", "/metrics/mem", cpmserverapi.MetricMEM},
		&rest.Route{"POST", "/metrics/cpu", cpmserverapi.MetricCPU},
		&rest.Route{"POST", "/docker/inspect", cpmserverapi.DockerInspect},
		&rest.Route{"POST", "/docker/remove", cpmserverapi.DockerRemove},
		&rest.Route{"POST", "/docker/start", cpmserverapi.DockerStart},
		&rest.Route{"POST", "/docker/stop", cpmserverapi.DockerStop},
		&rest.Route{"POST", "/docker/run", cpmserverapi.DockerRun},
		&rest.Route{"POST", "/disk/provision", cpmserverapi.DiskProvision},
		&rest.Route{"POST", "/disk/delete", cpmserverapi.DiskDelete},
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	log.Fatal(http.ListenAndServe(":10001", api.MakeHandler()))
	log.Fatal(http.ListenAndServeTLS(":10000", "/var/cpm/keys/cert.pem", "/var/cpm/keys/key.pem", api.MakeHandler()))
}
Exemple #19
0
// MakeHandler creates the api request handler
func MakeHandler() *http.Handler {
	api := rest.NewApi()

	authMiddleware, err := CreateAuthMiddleware()
	if err != nil {
		panic(err)
	}

	api.Use(&rest.IfMiddleware{
		// Only authenticate non login or register requests
		Condition: func(request *rest.Request) bool {
			return (request.URL.Path != variables.APIPathLoginUserServer) && (request.URL.Path != variables.APIPathRegisterUserServer)
		},
		IfTrue: authMiddleware,
	})
	api.Use(rest.DefaultProdStack...)
	router, err := rest.MakeRouter(
		rest.Post(variables.APIPathLoginUserServer, authMiddleware.LoginHandler),
		rest.Get(variables.APIPathRefreshUserServer, authMiddleware.RefreshHandler),
		rest.Post(variables.APIPathRegisterUserServer, PostRegister),
		rest.Get(variables.APIPathUserServer, GetUser),
		rest.Post(variables.APIPathUserServer, PostUser),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	handler := api.MakeHandler()
	return &handler
}
Exemple #20
0
func main() {
	dsn := fmt.Sprintf("user=%s dbname=%s sslmode=disable",
		os.Getenv("DATABASE_USER"),
		os.Getenv("DATABASE_NAME"))

	db, err := gorm.Open("postgres", dsn)

	fmt.Println(dsn)

	if err != nil {
		panic(err)
	}

	db.DB()
	db.DB().Ping()
	db.DB().SetMaxIdleConns(10)
	db.DB().SetMaxOpenConns(100)
	db.SingularTable(true)
	db.LogMode(true)

	api := rest.NewApi()

	api.Use(rest.DefaultDevStack...)

	accounts := &Accounts{Db: db}

	router, err := rest.MakeRouter(
		rest.Get("/users/:username", accounts.Detail),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
}
Exemple #21
0
func main() {
	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)

	router, err := rest.MakeRouter(
		rest.Get("/test", testApi),
		rest.Post("/addTask", plain.AddTask),
		rest.Get("/getTasks", plain.GetTasks),
		rest.Post("/removeTask", plain.RemoveTask),
		rest.Post("/completeTask", plain.CloseTask),
		rest.Post("/rearrangeTasks", plain.RearrangeTasks),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)

	http.Handle("/api/", http.StripPrefix("/api", api.MakeHandler()))
	http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("frontend"))))

	log.Println("Listening...")

	http.ListenAndServe(":3000", nil)

}
Exemple #22
0
func (this *App) Run() {
	apiServer := rest.NewApi()
	apiServer.Use(rest.DefaultDevStack...)

	// Cors
	apiServer.Use(&rest.CorsMiddleware{
		RejectNonCorsRequests: false,
		OriginValidator: func(origin string, request *rest.Request) bool {
			return true
		},
		AllowedMethods: []string{"GET", "POST", "PUT"},
		AllowedHeaders: []string{
			"Authorization", "Accept", "Content-Type", "X-Custom-Header", "Origin",
		},
		AccessControlAllowCredentials: true,
		AccessControlMaxAge:           3600,
	})

	// Jsonp
	apiServer.Use(&rest.JsonpMiddleware{
		CallbackNameKey: "jsonp",
	})

	router, err := rest.MakeRouter(config.Routes...)
	if err != nil {
		log.Fatal(err)
	}

	apiServer.SetApp(router)

	log.Info("Start serving, port=", this.Env.Port)
	log.Fatal(http.ListenAndServe(this.Port(), apiServer.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 main() {

	svmw := SemVerMiddleware{
		MinVersion: "1.0.0",
		MaxVersion: "3.0.0",
	}
	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	router, err := rest.MakeRouter(
		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)
	}
	api.SetApp(router)
	http.Handle("/api/", http.StripPrefix("/api", api.MakeHandler()))
	log.Fatal(http.ListenAndServe(":8080", nil))
}
func main() {
	flag.Parse()

	sm := newSyncMaster(*dbDir)
	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)

	router, err := rest.MakeRouter(
		&rest.Route{"GET", "/labels/since/:nonce/for/:mpk", sm.GetLabels},
		&rest.Route{"POST", "/label", sm.CreateLabel},
		&rest.Route{"POST", "/labels", sm.CreateLabels},
	)

	if err != nil {
		log.Fatal(err)
	}

	api.SetApp(router)
	sm.logger.Info("Server started and listening on %s", *listenPort)
	if *useTLS {
		sm.logger.Info("Using SSL with certificate '%s' and keyfile '%s'", *certPath, *keyPath)
		log.Fatal(http.ListenAndServeTLS(*listenPort, *certPath, *keyPath, api.MakeHandler()))
	} else {
		log.Fatal(http.ListenAndServe(*listenPort, api.MakeHandler()))
	}
}
Exemple #26
0
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 main() {
	jwt_middleware := &jwt.JWTMiddleware{
		Key:        []byte("secret key"),
		Realm:      "jwt auth",
		Timeout:    time.Hour,
		MaxRefresh: time.Hour * 24,
		Authenticator: func(userId string, password string) bool {
			return userId == "admin" && password == "admin"
		}}

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	// we use the IfMiddleware to remove certain paths from needing authentication
	api.Use(&rest.IfMiddleware{
		Condition: func(request *rest.Request) bool {
			return request.URL.Path != "/login"
		},
		IfTrue: jwt_middleware,
	})
	api_router, _ := rest.MakeRouter(
		rest.Post("/login", jwt_middleware.LoginHandler),
		rest.Get("/auth_test", handle_auth),
		rest.Get("/refresh_token", jwt_middleware.RefreshHandler),
	)
	api.SetApp(api_router)

	http.Handle("/api/", http.StripPrefix("/api", api.MakeHandler()))

	log.Fatal(http.ListenAndServe(":8080", nil))
}
Exemple #28
0
func main() {
	fmt.Printf("grouch: a RESTful object store.\n")

	// Open the config file
	config := readConfig("./config.json")
	fmt.Printf("Data directory: %s\n", config.Directory)
	fmt.Printf("Mode: %s\n", config.Mode)

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)

	endpoint := "/" + config.Directory + "/#file"
	router, err := rest.MakeRouter(
		rest.Get(endpoint, func(w rest.ResponseWriter, req *rest.Request) {
			file, err := ioutil.ReadFile(
				config.Directory + "/" + req.PathParam("file"))
			if err != nil {
				rest.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			fileContents := string(file)
			w.WriteJson(&fileContents)
		}),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
}
func startGoJsonRest() {
	api := rest.NewApi()
	router, _ := rest.MakeRouter(
		&rest.Route{HttpMethod: "GET", PathExp: "/hello", Func: goJsonRestHandler},
	)
	api.SetApp(router)
	http.ListenAndServe(":"+strconv.Itoa(port), api.MakeHandler())
}
Exemple #30
0
// Start start the http rest api plugin
func (cli *HTTPAPIServer) Start(config map[string]interface{}) error {

	wwwroot, _ := utils.GetString("static", config, "")
	addr, _ := utils.GetString("listen", config, ":8080")
	secret, ok := utils.GetString("secret", config, randomString(128))
	if !ok {
		logrus.Warnf("Plugins: httpapi: generated new secret: %s", secret)
	}

	jwt_middleware := &jwt.JWTMiddleware{
		Key:        []byte(secret),
		Realm:      "jwt auth",
		Timeout:    time.Hour,
		MaxRefresh: time.Hour * 24,
		Authenticator: func(userId string, password string) bool {
			return userId == "admin" && password == "admin"
		}}

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	api.Use(&rest.IfMiddleware{
		Condition: func(request *rest.Request) bool {
			return request.URL.Path != "/login"
		},
		IfTrue: jwt_middleware,
	})

	router, err := rest.MakeRouter(
		rest.Post("/login", jwt_middleware.LoginHandler),
		rest.Get("/refresh_token", jwt_middleware.RefreshHandler),

		rest.Get("/", getApiVersion),
		rest.Get("/sensors", getAllSensors),
		rest.Get("/sensors/:backend.:sensor", getSensor),
		rest.Get("/services", getAllServices),
		rest.Get("/services/:backend.:service", getService),
		rest.Post("/services/:backend.:service", callService),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)

	http.Handle("/v1/", http.StripPrefix("/v1", api.MakeHandler()))

	if wwwroot != "" {
		logrus.Infof("Plugin: httpapi: service static content from %s", wwwroot)
		http.Handle("/ui/", http.StripPrefix("/ui", http.FileServer(http.Dir(wwwroot))))
	}

	go func() {
		logrus.Infof("Plugin: httpapi: starting on %s", addr)
		manners.ListenAndServe(addr, http.DefaultServeMux)
	}()

	return nil
}