func init() { users = map[string]user{ "1": user{ ID: "1", Name: "Wreck-It Ralph", }, } // hook into the echo instance to create an endpoint group // and add specific middleware to it plus handlers g := e.Group("/users") g.Use(middleware.CORS()) g.POST("", createUser) g.GET("", getUsers) g.GET("/:id", getUser) }
// Serve sets up and starts the server func (s *APIServer) Serve() error { e := echo.New() e.Debug = true e.Use(middleware.Logger()) e.Use(middleware.Recover()) e.Use(middleware.CORS()) e.Use(middleware.BodyLimit("1024K")) e.Use(middleware.Gzip()) // Serve the ember app e.File("/", "assets/index.html") e.Static("/assets", "assets/assets") // e.OPTIONS("/api/login/", s.updateUser) e.POST("/api/login/", s.login) // Restricted group r := e.Group("/api/v1") r.Use(middleware.JWT([]byte("secret"))) r.Use(s.getDBUser) r.GET("/feeds", s.getFeeds) r.POST("/feeds", s.addFeed) r.GET("/feeds/:id", s.getFeed) r.PATCH("/feeds/:id", s.updateFeed) r.PUT("/feeds/:id/subscribe", s.subFeed) r.PUT("/feeds/:id/unsubscribe", s.unsubFeed) customServer := &http.Server{ Addr: fmt.Sprintf(":%d", s.Port), ReadTimeout: 20 * time.Second, WriteTimeout: 20 * time.Second, MaxHeaderBytes: 2048, } err := e.StartServer(customServer) if err != nil { return fmt.Errorf("Error starting server: %s", err) } return nil }
func main() { runtime.GOMAXPROCS(runtime.NumCPU()) data := ` defaults: base_uri: http://static.turfmedia.com/ sites: ph: settings: affiliate-id: 2a848818 zones: top: banner728x90 middle: banner728x90 banners: banner728x90: #skyscraper - image: turfistar/3481d796.png url: "http://turfistar.com/#a_aid=2a848818&a_bid=3481d796" - image: pronostic-facile/0eca889d.png url: "http://www.pronostic-facile.fr?a_aid=2a848818&a_bid=0eca889d" - image: gazette-turf/8d3376b4.png url: "http://gazette-turf.fr/#a_aid=2a848818&a_bid=8d3376b4" ` // data, err := ioutil.ReadFile("config.yml") // if err != nil { // println("File does not exist:", err.Error()) // os.Exit(1) // } // data, err := Asset("config.yml") // if err != nil { // println("config not found:", err.Error()) // os.Exit(1) // } var config Config if err := config.parse([]byte(data)); err != nil { log.Fatal(err) } // fmt.Printf("%#v\n", config) e := echo.New() e.Use(middleware.CORS()) e.GET("/zones/:site/:id", func(c echo.Context) error { zone := c.Param("id") site := c.Param("site") if config.Sites[site].Zones[zone] != "" { c.Response().Header().Set("Cache-Control", "max-age=59") return c.String(http.StatusOK, getBanner(site, zone, &config)) } return c.String(http.StatusNotFound, "Not Found") }) e.Static("/", "ads") e.Run(fasthttp.New(":1323")) }
func main() { // 获取执行参数 conf_path := flag.String("conf", "", "配置文件路径") flag.Parse() // 获取配置文件的路径 base_utils.CompletePath(conf_path) // 初始化log日志系统 conf, err := base_utils.ConfigInit(*conf_path) if err != nil { re_act.Error() os.Exit(2) } // 初始化系统日志 re_act.InitLog(conf.MicroSer["log1"]) // 记录系统日志 log := types.NewSystemLog() log.Type = "system" log.Msg = "start " re_act.Info(log) // 初始化控制层 err = handler.Init() if err != nil { fmt.Println("handler初始化失败:", err) os.Exit(2) } // 选择数据序列化方式 (proto , json) selectProto("json") // echo引擎 e := echo.New() // 调试测试 e.Use(mw.Logger()) e.Use(mw.Recover()) // 添加跨域 cors e.Use(mw.CORS()) // 容器 //e.Get("/pod", podGet) //e.Post("/pod", podPost) //e.Put("/pod", podPut) //e.Patch("/pod", podPatch) //e.Delete("/pod", podDelete) // 容器网络 //e.Get("/ser", podGet) //e.Post("/ser", podPost) //e.Put("/ser", podPut) //e.Patch("/ser", podPatch) //e.Delete("/ser", podDelete) // 应用 e.Get("/app", appGet) e.Post("/app", appPost) e.Put("/app", podPut) e.Patch("/app", podPatch) e.Delete("/app", podDelete) // 应用模板 e.Get("/app/temp", appTempGet) //e.Post("/app/temp", podPost) //e.Put("/app/temp", podPut) //e.Patch("/app/temp", podPatch) //e.Delete("/app/temp", podDelete) // 用户 e.Get("/user", podGet) e.Post("/user", podPost) e.Put("/user", podPut) e.Patch("/user", podPatch) e.Delete("/user", podDelete) // 服务信息 e.Get("/version", version) e.Get("/info", info) e.Get("/api/map", info) // 运行http服务器 e.Run(fasthttp.New(":1234")) }
func main() { logrus.Println("running migrations") allErrors, ok := migrate.UpSync(dbAddr, "./migrations") if !ok { logrus.Println("Oh no ...") logrus.Fatal(allErrors) // do sth with allErrors slice } // Echo instance e := echo.New() e.Use(mw.LoggerWithConfig(mw.LoggerConfig{ Format: "method=${method}, uri=${uri}, status=${status}\n", })) e.Use(mw.Recover()) e.Use(mw.CORS()) s := store.Connect(dbAddr) s.EnsureAdmin() e.Use(h.SetDB(s)) // catch sql no rows errors and return as a 404 // e.Use(func(h echo.HandlerFunc) echo.HandlerFunc { // return func(c echo.Context) error { // err := h(c) // if err == store.ErrNoRows { // return echo.NewHTTPError(http.StatusNotFound) // } // return err // } // }) // e.Post("/session", h.CreateSession(signingkey, signingmethod)) e.Post("/activate/:token", h.ActivateAccount) e.Get("/setup", h.CanSetup) e.Post("/setup", h.SetupApp) decoded, err := base64.URLEncoding.DecodeString(signingkey) if err != nil { panic(err) } auth := e.Group("") auth.Use(mw.JWT(decoded)) auth.Get("/me", h.GetSession) // Accounts auth.Get("/account", h.GetAllAccounts) auth.Post("/account", h.CreateAccount) auth.Delete("/account/:id", h.DeleteAccount) // People g := auth.Group("/person") g.GET("", h.GetAllPeople) g.POST("", h.CreatePerson) g.GET("/:id", h.GetPerson) g.PUT("/:id", h.UpdatePerson) g.DELETE("/:id", h.DeletePerson) // Courses g = auth.Group("/course") g.GET("", h.GetAllCourses) g.POST("", h.CreateCourse) g.GET("/:id", h.GetCourse) g.PUT("/:id", h.UpdateCourse) g.PUT("/:courseID/term/:termID", h.CreateCourseTerm) g.DELETE("/:id", h.DeleteCourse) g.GET("/:courseID/term/:termID/assignments", h.GetCourseAssignments) g.GET("/:courseID/term/:termID/gradebook", h.GetGradebook) // Attempt g = auth.Group("/attempt") g.GET("", h.GetAllAttempts) g.POST("", h.CreateAttempt) g.GET("/:id", h.GetAttempt) g.PUT("/:id", h.UpdateAttempt) g.DELETE("/:id", h.DeleteAttempt) // Announcement g = auth.Group("/announcement") g.GET("", h.GetAllAnnouncements) g.POST("", h.CreateAnnouncement) g.GET("/:id", h.GetAnnouncement) g.PUT("/:id", h.UpdateAnnouncement) g.DELETE("/:id", h.DeleteAnnouncement) // Enrollments g = auth.Group("/enrollment") g.GET("", h.GetAllEnrollments) g.POST("", h.CreateEnrollment) g.GET("/:id", h.GetEnrollment) g.PUT("/:id", h.UpdateEnrollment) g.DELETE("/:id", h.DeleteEnrollment) // Terms g = auth.Group("/term") g.GET("", h.GetAllTerms) g.POST("", h.CreateTerm) g.GET("/:id", h.GetTerm) g.PUT("/:id", h.UpdateTerm) g.DELETE("/:id", h.DeleteTerm) // Levels g = auth.Group("/level") g.GET("", h.GetAllLevels) g.POST("", h.CreateLevel) g.GET("/:id", h.GetLevel) g.PUT("/:id", h.UpdateLevel) g.DELETE("/:id", h.DeleteLevel) // Assignments g = auth.Group("/assignment") g.GET("", h.GetAllAssignments) g.POST("", h.CreateAssignment) g.GET("/:id", h.GetAssignment) g.PUT("/:id", h.UpdateAssignment) g.DELETE("/:id", h.DeleteAssignment) // AssignmentGroups g = auth.Group("/group") g.GET("", h.GetAllAssignmentGroups) g.POST("", h.CreateAssignmentGroup) g.GET("/:id", h.GetAssignmentGroup) g.PUT("/:id", h.UpdateAssignmentGroup) g.DELETE("/:id", h.DeleteAssignmentGroup) // AssignmentGrades g = auth.Group("/grade") // Start server logrus.Println("Listening On:", port) e.Run(standard.New(":" + port)) }
func main() { // Echo instance e := echo.New() // Middleware echo e.Use(middleware.Logger()) logg := e.Logger() e.Use(middleware.Recover()) e.Use(middleware.Gzip()) e.Use(middleware.Secure()) e.Use(middleware.CORS()) e.Use(middleware.BodyLimit("200M")) // gopkg.in/mgo.v2 db := midd.NewMgo(viper.GetString("db.url"), viper.GetString("db.name")) defer db.Session.Close() e.Use(midd.Mgo(db)) // github.com/thoas/stats middStat := stats.New() e.Use(standard.WrapMiddleware(middStat.Handler)) // Route for stats e.Get("/stats", echo.HandlerFunc(func(c echo.Context) error { return c.JSON(http.StatusOK, middStat.Data()) })) // API v1 Restricted group Token in header api := e.Group("/apiv1") api.Use(middleware.JWTWithConfig(middleware.JWTConfig{ SigningKey: []byte(midd.SigningKey), TokenLookup: "header:Authorization"})) api.Post("/user", handler.PostUser) api.Get("/user/:id", handler.GetUser) // API v1 Token as first param apit := e.Group("/apiv1token") apit.Use(middleware.JWTWithConfig(middleware.JWTConfig{ SigningKey: []byte(midd.SigningKey), TokenLookup: "query:token"})) apit.Post("/user", handler.PostUser) apit.Get("/user/:id", handler.GetUser) // Serve index file e.File("/", "public/index.html") // Serve favicon e.File("/favicon.ico", "public/favicon.ico") // Serve static files e.Static("/scripts", "public/scripts") midd.GenerateToken() // Get server info var svrHostname string if runtime.GOOS == "windows" { svrHostname = fmt.Sprintf("%s.%s", os.Getenv("COMPUTERNAME"), os.Getenv("USERDNSDOMAIN")) } else { svrHostname, _ = os.Hostname() } webInterfacePort := viper.GetString("web.interface") logg.Printf("%s for %s %s on %d cores\n%s%s\n", runtime.Version(), runtime.GOOS, runtime.GOARCH, runtime.NumCPU(), svrHostname, webInterfacePort) mgoInfo, _ := db.Session.BuildInfo() logg.Printf("MongoDB %s %d bits\n", mgoInfo.Version, mgoInfo.Bits) // github.com/tylerb/graceful std := standard.New(webInterfacePort) std.SetHandler(e) graceful.ListenAndServe(std.Server, 5*time.Second) }