func main() { wd, _ := os.Getwd() log.Println("Working directory", wd) // We need `./db/`... if dbStat, err := os.Stat(`./db`); err != nil || !dbStat.IsDir() { os.Mkdir(`./db`, 0700) } loadSettings("db/app.ini") log.Println("Writing logs to ", Settings.LogFile) if Settings.LogFile != "" { f, err := os.OpenFile(Settings.LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { log.Printf("Can't open logfile! `%s` | Error: %#v\n", Settings.LogFile, err) os.Exit(1) } defer f.Close() log.SetOutput(f) } jobList := service.NewJobList() taskList := service.NewTaskList() triggerList := service.NewTriggerList() runList := service.NewRunList(jobList) jobList.Load() taskList.Load() triggerList.Load() runList.Load() hub := service.NewHub(runList) go hub.HubLoop() executor := service.NewExecutor(jobList, taskList, runList) appContext := &ctx{hub, executor, jobList, taskList, triggerList, runList} r := mux.NewRouter() // non REST routes r.PathPrefix("/static/").Handler(http.FileServer(http.Dir("web/"))) r.HandleFunc("/", app).Methods("GET") r.HandleFunc("/favicon.ico", favicon).Methods("GET") r.Handle("/ws", appHandler{appContext, wsHandler}).Methods("GET") for _, detail := range routes { r.Handle(detail.route, appHandler{appContext, detail.handler}).Methods(detail.method) } host := Settings.ServeIP + ":" + strconv.Itoa(Settings.HTTPPort) log.Println("Running on " + host) if Settings.LogFile == "" { log.Println("Not logging to file, restart disabled...") http.ListenAndServe(host, r) } else { endless.ListenAndServe(host, r) } }
func main() { log.Print("Starting net/http server on 8000") http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { time.Sleep(2 * time.Second) fmt.Fprintf(w, "Hello %q\n", html.EscapeString(r.URL.Path)) }) err := endless.ListenAndServe(":8000", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
func Serve(port string, handlers []RpcHandler) { r := mux.NewRouter() for _, handler := range handlers { s := rpc.NewServer() s.RegisterCodec(json2.NewCodec(), "application/json") s.RegisterService(handler.Service, "") r.Handle(handler.Path, s) } endless.DefaultHammerTime = -1 endless.ListenAndServe(":"+port, r) }
func startHttpServer() { router := gin.New() // don't need to use Logger, if we use apache/nginx. router.Use(gin.Recovery()) routes.Use(router) if gin.Mode() == gin.ReleaseMode { logger.Infof("GIN Listening and serving HTTP on %s", listenPort) endless.ListenAndServe(listenPort, router) // use endless for graceful restart/stop. } else { router.Run(listenPort) } }
func main() { mux1 := mux.NewRouter() mux1.HandleFunc("/hello", handler). Methods("GET") err := endless.ListenAndServe("localhost:4242", mux1) if err != nil { log.Println(err) } log.Println("Server on 4242 stopped") os.Exit(0) }
func main() { // endless.DefaultHammerTime = 10*time.Second mux := mux.NewRouter() mux.HandleFunc("/foo", handler). Methods("GET") err := endless.ListenAndServe("localhost:4242", mux) if err != nil { log.Println(err) } log.Println("Server on 4242 stopped") os.Exit(0) }
func main() { mux1 := mux.NewRouter() mux1.HandleFunc("/hello", handler). Methods("GET") mux1.HandleFunc("/foo", handlerFoo). Methods("GET") mux2 := mux.NewRouter() mux2.HandleFunc("/bar", handlerBar). Methods("GET") log.Println("Starting servers...") w := sync.WaitGroup{} w.Add(2) go func() { time.Sleep(time.Second) err := endless.ListenAndServe("localhost:4242", mux1) if err != nil { log.Println(err) } log.Println("Server on 4242 stopped") w.Done() }() go func() { err := endless.ListenAndServe("localhost:4243", mux2) if err != nil { log.Println(err) } log.Println("Server on 4243 stopped") w.Done() }() w.Wait() log.Println("All servers stopped. Exiting.") os.Exit(0) }
func main() { services.InitDb() defer LogErr() defer services.DB.Close() //routes router := httprouter.New() router.HandleMethodNotAllowed = false router.NotFound = http.HandlerFunc(NotFoundHandler) router.GET("/balance", controllers.GetBalance) router.POST("/deposite", controllers.AddAmount) router.POST("/withdraw", controllers.WithdrawAmount) router.POST("/transfer", controllers.TransferAmount) //start http Log.Printf("started at port: %s", Port) Log.Fatal(endless.ListenAndServe(":"+Port, router)) }
func main() { services.InitDb() defer LogErr() defer services.DB.Close() //routes router := httprouter.New() router.HandleMethodNotAllowed = false router.NotFound = http.HandlerFunc(NotFoundHandler) router.POST("/api/v1/model.find_by_name", controllers.GetModelByName) //close old app and write new pid ReplacePid() endless.DefaultHammerTime = -1 //start http Log.Printf("started at port: %s", Port) Log.Fatal(endless.ListenAndServe(":"+Port, router)) }
func main() { flag.Parse() // To serve a directory on disk (/tmp) under an alternate URL // path (/tmpfiles/), use StripPrefix to modify the request // URL's path before the FileServer sees it: http.HandleFunc("/", IndexHandler) http.Handle("/swagger-ui/", http.StripPrefix("/swagger-ui/", http.FileServer(http.Dir(*staticContent)))) for apiKey, _ := range apiDescriptionsJson { http.HandleFunc("/"+apiKey+"/", ApiDescriptionHandler) } listenTo := *host + ":" + *port log.Info("Star listen to %s", listenTo) err := endless.ListenAndServe(listenTo, http.DefaultServeMux) if err != nil { log.Error(err.Error()) } log.Info("Server on %s stopped", listenTo) os.Exit(0) }
func main() { http.HandleFunc("/", hello) endless.ListenAndServe(":8000", nil) }
//Run main entry func Run() error { app := cli.NewApp() app.Name = "chaos" app.Version = "v20160606" app.Usage = "it-package web application." app.EnableBashCompletion = true app.Commands = []cli.Command{ { Name: "init", Aliases: []string{"i"}, Usage: "init config file", Flags: []cli.Flag{ cli.StringFlag{ Name: "environment, e", Value: "development", Usage: "environment, like: development, production, test...", }, }, Action: func(c *cli.Context) error { const fn = "config.toml" if _, err := os.Stat(fn); err == nil { return fmt.Errorf("file %s already exists", fn) } fmt.Printf("generate file %s\n", fn) viper.Set("env", c.String("environment")) args := viper.AllSettings() fd, err := os.Create(fn) if err != nil { log.Println(err) return err } defer fd.Close() end := toml.NewEncoder(fd) err = end.Encode(args) return err }, }, { Name: "server", Aliases: []string{"s"}, Usage: "start the app server", Action: IocAction(func(*cli.Context, *inject.Graph) error { if IsProduction() { gin.SetMode(gin.ReleaseMode) } rt := gin.Default() rt.Use(i18n.LocaleHandler) Loop(func(en Engine) error { en.Mount(rt) return nil }) adr := fmt.Sprintf(":%d", viper.GetInt("http.port")) hnd := cors.New(cors.Options{ AllowCredentials: true, AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "PATCH"}, AllowedHeaders: []string{"*"}, //Debug: true, }).Handler(rt) if IsProduction() { return endless.ListenAndServe(adr, hnd) } return http.ListenAndServe(adr, hnd) }), }, { Name: "worker", Aliases: []string{"w"}, Usage: "start the worker progress", Action: IocAction(func(*cli.Context, *inject.Graph) error { Loop(func(en Engine) error { en.Worker() return nil }) workers.Run() return nil }), }, { Name: "openssl", Aliases: []string{"ssl"}, Usage: "generate ssl certificates", Flags: []cli.Flag{ cli.StringFlag{ Name: "name, n", Usage: "name", }, cli.StringFlag{ Name: "country, c", Value: "Earth", Usage: "country", }, cli.StringFlag{ Name: "organization, o", Value: "Mother Nature", Usage: "organization", }, cli.IntFlag{ Name: "years, y", Value: 1, Usage: "years", }, }, Action: Action(func(c *cli.Context) error { name := c.String("name") if len(name) == 0 { cli.ShowCommandHelp(c, "openssl") return nil } root := path.Join("etc", "ssl", name) key, crt, err := CreateCertificate( true, pkix.Name{ Country: []string{c.String("country")}, Organization: []string{c.String("organization")}, }, c.Int("years"), ) if err != nil { return err } fnk := path.Join(root, "key.pem") fnc := path.Join(root, "crt.pem") fmt.Printf("generate pem file %s\n", fnk) err = WritePemFile(fnk, "RSA PRIVATE KEY", key) fmt.Printf("test: openssl rsa -noout -text -in %s\n", fnk) if err == nil { fmt.Printf("generate pem file %s\n", fnc) err = WritePemFile(fnc, "CERTIFICATE", crt) fmt.Printf("test: openssl x509 -noout -text -in %s\n", fnc) } if err == nil { fmt.Printf( "verify: diff <(openssl rsa -noout -modulus -in %s) <(openssl x509 -noout -modulus -in %s)", fnk, fnc, ) } return err }), }, } for _, en := range engines { cmd := en.Shell() app.Commands = append(app.Commands, cmd...) } return app.Run(os.Args) }