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())) }
// 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 }
/* 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 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)) }
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 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 (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() { 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())) }
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) }
func (a *RestAdapterImplementation) Init(db models.DB) (router rest.App, err error) { a.db = db router, err = rest.MakeRouter( rest.Get("/feeds/:id", a.GetFeed), rest.Get("/feeds", a.GetAllFeeds), rest.Get("/tags", a.GetAllTags), ) 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() { 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() { DataFile, err := os.Open(configFile) if err != nil { log.Fatal("Error opening Config file", err.Error()) os.Exit(2) } jsonParser := json.NewDecoder(DataFile) if err = jsonParser.Decode(&serverData); err != nil { log.Fatal("Error parsing config file", err.Error()) os.Exit(2) } Println(timeNow, " --- Config file ", configFile, " loaded") Println(timeNow, " --- Starting web server listener on host:", serverData.Host, "on port:", serverData.Port) 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), rest.Get("/index", Index), rest.Get("/messages", GetAllMessages), rest.Post("/messages", PostMessage), rest.Get("/countries/:code", GetMessage), // rest.Delete("/countries/:code", DeleteMessage), ) api.SetApp(api_router) http.Handle("/api/", http.StripPrefix("/api", api.MakeHandler())) log.Fatal(http.ListenAndServe(serverData.Host+":"+serverData.Port, 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)) }
// Serve a json api func Serve() { redisPool = newPool(redisServer, redisPassword) api := rest.NewApi() api.Use(&rest.IfMiddleware{ Condition: func(request *rest.Request) bool { return request.URL.Path != "/login" }, IfTrue: &tokenauth.AuthTokenMiddleware{ Realm: authRealm, Authenticator: func(token string) string { rd := redisPool.Get() defer rd.Close() user, _ := redis.String(rd.Do("GET", tokenNamespace+tokenauth.Hash(token))) return user }, }, IfFalse: &rest.AuthBasicMiddleware{ Realm: authRealm, Authenticator: func(user string, password string) bool { if user == "user" && password == "password" { return true } return false }, }, }) api.Use(rest.DefaultDevStack...) router, err := rest.MakeRouter( rest.Post("/login", login), rest.Get("/containers", list), rest.Get("/container/:id", inspect), rest.Post("/image/build", build), rest.Post("/image/run", create), rest.Get("/container/start/:id", start), rest.Get("/container/stop/:id", stop), ) if err != nil { log.Fatal(err) } api.SetApp(router) log.Println("Port", port) log.Fatal(http.ListenAndServe(":"+port, 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() { 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())) }
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() { 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()) }
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 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())) }
// 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 }
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())) }
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("now begin to run server, please wait...") api := rest.NewApi() api.Use(rest.DefaultDevStack...) route, _ := rest.MakeRouter( rest.Post("/simpledeploy/apps", deploySimpleHandler), rest.Get("/info", appInfoHandler), rest.Get("/info/#appId", appDetailInfoHandler), ) api.SetApp(route) fileServer := http.FileServer(http.Dir(os.Getenv("GOPATH") + STATIC_DIR)) http.HandleFunc("/", entranceGuarder(indexHandler)) http.Handle("/static/", http.StripPrefix("/static", fileServer)) http.Handle("/api/", http.StripPrefix("/api", api.MakeHandler())) http.ListenAndServe(":8080", nil) }
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 MakeAPI() *rest.Api { mdb := NewMeterDB() api := rest.NewApi() api.Use(rest.DefaultDevStack...) router, err := rest.MakeRouter( rest.Get("/message", func(w rest.ResponseWriter, req *rest.Request) { w.WriteJson(map[string]string{"Body": "Hello World!"}) }), rest.Get("/currentabsolutevalues", mdb.GetCurrentAbsoluteValues), rest.Get("/values/#meter", mdb.GetValues), ) if err != nil { log.Fatal(err) } api.SetApp(router) return api }