func main() { bind_addr := flag.String("bind_ip", "127.0.0.1", "bind ip address") http_port := flag.Int("http_port", 9999, "listen http port") rpc_port := flag.Int("rpc_port", 9998, "listen rpc port") flag.Parse() go func() { addr, _ := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", *bind_addr, *rpc_port)) listener, _ := net.ListenTCP("tcp", addr) rpcservice := new(RPCService) rpc.Register(rpcservice) rpc.HandleHTTP() for { conn, _ := listener.Accept() go rpc.ServeCodec(jsonrpc.NewServerCodec(conn)) } }() web.Get("/api/topics/([a-zA-Z0-9_\\-]+)/subscribers/([a-zA-Z0-9_\\-]+)/messages", APIGetTopicMessages) web.Post("/api/topics/([a-zA-Z0-9_\\-]+)/subscribers/([a-zA-Z0-9_\\-]+)/messages", APIPostTopicMessage) web.Get("/api/topics/([a-zA-Z0-9_\\-]+)", APIGetTopic) web.Post("/api/topics/([a-zA-Z0-9_\\-]+)", APIUpdateTopic) //web.Get("/api/topics", APIGetTopics) web.Get("/api/subscribers/([a-zA-Z0-9_\\-]+)", APIGetSubscriber) web.Post("/api/subscribers/([a-zA-Z0-9_\\-]+)", APIUpdateSubscriber) //web.Get("/api/topics/(.+)/subscribers/(.+)", APIGetTopicSubscriber) //web.Get("/api/topics/(.+)/subscribers", APIGetTopicSubscribers) web.Run(fmt.Sprintf("%s:%d", *bind_addr, *http_port)) }
func main() { viewInit() web.Config.CookieSecret = "UXVpZXJvIGEgbWkgcGVxdWXxbyBoaWpvIE1hcmNvcw==" // Init API library jailgo.EntryInit() jailgo.ArtInit() jailgo.LoginInit() // Principal, comment and search pages web.Get("/", showblog) web.Get("/comment(.*)", entry) web.Get("/search", search) // Editing articles and comments web.Post("/updateArt", updateArt) web.Post("/updateEntry", updateEntry) // Login and Administration web.Post("/login", login) web.Get("/admin", admin) // Web server web.Run("0.0.0.0:9085") }
func main() { pckg_dir = os.Getenv("GOPATH") + "/src/github.com/couchbaselabs/showfast/" web.Config.StaticDir = pckg_dir + "app" config_file, err := ioutil.ReadFile(pckg_dir + "config.json") if err != nil { log.Fatal(err) } var config Config err = json.Unmarshal(config_file, &config) if err != nil { log.Fatal(err) } data_source = DataSource{config.CouchbaseAddress, config.BucketPassword} web.Get("/", home) web.Get("/admin", admin) web.Get("/release", release) web.Get("/feed", feed) web.Get("/all_metrics", data_source.GetAllMetrics) web.Get("/all_clusters", data_source.GetAllClusters) web.Get("/all_timelines", data_source.GetAllTimelines) web.Get("/all_benchmarks", data_source.GetAllBenchmarks) web.Get("/all_runs", all_runs) web.Get("/all_releases", data_source.GetAllReleases) web.Get("/all_feed_records", data_source.GetAllFeedRecords) web.Get("/get_comparison", get_comparison) web.Post("/delete", delete) web.Post("/reverse_obsolete", reverse_obsolete) web.Run(config.ListenAddress) }
// Site is ie. "archlinux.no" and used for sending confirmation emails func (ue *UserEngine) ServePages(site string) { state := ue.state web.Post("/register/(.*)", GenerateRegisterUser(state, site)) web.Post("/register", GenerateNoJavascriptMessage()) web.Post("/login/(.*)", GenerateLoginUser(state)) web.Post("/login", GenerateNoJavascriptMessage()) web.Get("/logout", GenerateLogoutCurrentUser(state)) web.Get("/confirm/(.*)", GenerateConfirmUser(state)) }
func main() { parse_flags() var config ViaConfig var configFile string args := flag.Args() if len(args) < 1 { configFile = "production.json" } else { configFile = args[0] } log.Print("loading config from " + configFile + "... ") config, err := LoadConfig(configFile) if err != nil { log.Printf("failed: %s\n", configFile, err.Error()) return } // Handle SIGINT and SIGKILL c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, os.Kill, syscall.SIGABRT) go func() { for sig := range c { log.Printf("received %v, exiting...", sig) os.Exit(1) } }() procs := runtime.NumCPU() runtime.GOMAXPROCS(procs) log.Printf("starting server, running on %d cores...", procs) via := NewVia(Debug, expiry, config.DataDir) server := Server{Via: via, Host: config.Host, Port: config.Port, AllowedCountries: config.AllowedCountries} // Basic web.Get("/", Splash) web.Get("/status", server.GetServerStatus) // Dmatrix web.Post("/matrix/", server.PostMatrix) // Path web.Post("/paths", server.PostPaths) web.Match("OPTIONS", "/(.*)", Options) go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }() web.Run(fmt.Sprintf("%s:%d", config.Host, config.Port)) }
func (srv *Server) Serve() { web.Get("/job/list", jobList) web.Get("/task/list", taskList) web.Get("/job/(.*)", jobGet) web.Post("/job", jobNew) web.Post("/job/run/(.*)", jobRun) web.Delete("/job/(.*)", jobRemove) web.Put("/job/(.*)", jobUpdate) addr, _ := globalCfg.ReadString("http_addr", ":9090") web.Run(addr) }
func main() { web.Get("/", views.Index) web.Get("/manage", views.Manage) web.Get("/manage/create", views.Create) web.Post("/manage/create", views.Create) web.Get("/manage/existing", views.Existing) web.Get("/manage/existing/remove/(.*)", views.Remove) web.Post("/manage/existing/remove/(.*)", views.Remove) web.Get("/manage/existing/(.*)", views.ExistingEdit) web.Post("/manage/existing/(.*)", views.ExistingEdit) web.Run("0.0.0.0:9999") }
func AttachAdmin(url string) { web.Get(url+"unpublished/(\\d+)?", unpublishedList) web.Get(url+"posts/(\\d+)?", postList) app.GetPost(url+"posts/edit/(.*)", postEdit) web.Get(url+"posts/delete/(.*)", postDelete) app.GetPost(url+"posts/add/", postAdd) web.Post(url+"posts/preview/", postPreview) // pages app.GetPost(url+"pages/add/", pageAdd) app.GetPost(url+"pages/edit/(.*)", pageEdit) web.Post(url+"pages/preview/", pagePreview) web.Get(url+"pages/delete/(.*)", pageDelete) web.Get(url+"pages/(\\d+)?", pageList) }
// Initialize and run the web app. func Reader() { readState() saveTicker := time.NewTicker(15 * time.Second) go saver(saveTicker) updateTicker := time.NewTicker(12 * time.Hour) go updater(updateTicker) web.Get("/", index) web.Post("/markAsRead", markAsRead) web.Post("/add", addNewFeed) web.Run("0.0.0.0:9090") }
func main() { initDummys() web.Get("/Home", renderPage) web.Get("/Splash", renderSplash) web.Get("/ProfileCard", renderProfile) web.Get("/CSS/(.*)", renderCSS) web.Get("/JS/(.*)", renderJS) web.Get("/Stream", renderStream) web.Get("/StreamItem", renderStreamItem) web.Post("/StreamItem", addStreamItem) web.Get("/Follows", renderFollow) web.Post("/Follow", addFollow) web.Run("0.0.0.0:9998") }
func (ce *ChatEngine) ServePages(basecp BaseCP, menuEntries MenuEntries) { chatCP := basecp(ce.state) chatCP.ContentTitle = "Chat" chatCP.ExtraCSSurls = append(chatCP.ExtraCSSurls, "/css/chat.css") tvgf := DynamicMenuFactoryGenerator(menuEntries) tvg := tvgf(ce.state) web.Get("/chat", chatCP.WrapSimpleContextHandle(ce.GenerateChatCurrentUser(), tvg)) web.Post("/say", ce.GenerateSayCurrentUser()) web.Get("/css/chat.css", ce.GenerateCSS(chatCP.ColorScheme)) web.Post("/setchatlines", ce.GenerateSetChatLinesCurrentUser()) // For debugging web.Get("/getchatlines", ce.GenerateGetChatLinesCurrentUser()) }
func main() { web.Get("/", indexPage) web.Post("/upload/(.*)", uploader) web.Get("/download/(.*)", downloader) bindHost := flag.String("bind", "0.0.0.0:8000", "bind to this address:port") realHost := flag.String("real-host", "", "real hostname client use to connect") realScheme := flag.String("real-scheme", "", "real scheme client use to connect") useXForwardedFor := flag.Bool("use-x-forwarded-for", false, "use X-Forwarded-For header for logging") logfile := flag.String("logfile", "", "log file (defaulg: stderr)") flag.Parse() appConfig = AppConfig{ *realScheme, *realHost, "http", *bindHost, *useXForwardedFor, } if *logfile != "" { web.SetLogger(NewRotateLog(*logfile, 1024*1024, 10, "", log.Ldate|log.Ltime)) } web.Run(appConfig.BindHost) }
func RegisterWebHook(hook Hook) { fmt.Println("Registering web-hook:", hook.Name(), "on", hook.Path()) hook.SetMessageChan(msgsystem.MessagesOut) Hooks = append(Hooks, &hook) web.Post(hook.Path(), hook.Request) }
func (we *WikiEngine) ServePages(basecp BaseCP, menuEntries MenuEntries) { wikiCP := basecp(we.state) wikiCP.ContentTitle = "Wiki" wikiCP.ExtraCSSurls = append(wikiCP.ExtraCSSurls, "/css/wiki.css") tvgf := DynamicMenuFactoryGenerator(menuEntries) tvg := tvgf(we.state) web.Get("/wiki", we.GenerateWikiRedirect()) // Redirect to /wiki/main web.Get("/wikiedit/(.*)", wikiCP.WrapWebHandle(we.GenerateWikiEditForm(), tvg)) // Form for editing wiki pages web.Get("/wikisource/(.*)", wikiCP.WrapWebHandle(we.GenerateWikiViewSource(), tvg)) // Page for viewing the source web.Get("/wikidelete/(.*)", wikiCP.WrapWebHandle(we.GenerateWikiDeleteForm(), tvg)) // Form for deleting wiki pages web.Get("/wiki/(.*)", wikiCP.WrapWebHandle(we.GenerateShowWiki(), tvg)) // Displaying wiki pages web.Get("/wikipages", wikiCP.WrapSimpleContextHandle(we.GenerateListPages(), tvg)) // Listing wiki pages web.Post("/wiki", we.GenerateCreateOrUpdateWiki()) // Create or update pages web.Post("/wikideletenow", we.GenerateDeleteWikiNow()) // Delete pages (admin only) web.Get("/css/wiki.css", we.GenerateCSS(wikiCP.ColorScheme)) // CSS that is specific for wiki pages }
func Routes() { // "Brain" stuff web.Get("/scoreboard", getScoreboard) web.Get("/publicUsers", getPublicUsers) web.Put("/validateFlag", domainHandler(validateFlag)) // To be implemented ? web.Post("/newuser", domainHandler(newUser)) }
func main() { conn, err = redis.Dial("tcp", ":6379") if err != nil { // handle error } defer conn.Close() web.Post("(.*)", handleFilter) web.Run("0.0.0.0:9999") }
func main() { DBConnect() defer DBDisconnect() web.Config.CookieSecret = "7C19QRmwf3mHZ9CPAaPQ0hsWeufKd" web.Get("/", index) web.Get("/month", month) web.Get("/post", post) web.Get("/rss.xml", rss) web.Get("/index.php/feed/", rss) web.Get("/index.php/feed/atom/", rss) web.Get("/admin/edit", editGet) web.Post("/admin/edit", editPost) web.Get("/admin", adminGet) web.Post("/admin", adminPost) web.Run("0.0.0.0:9876") }
// StartServer starts the Zilch Web Server. func StartServer(resourceDir, port string) { start := time.Now() database, _ := NewDatabase(resourceDir) zcc := ZipCodeController{database} pc := PngController{database} sc := StaticController{} web.Get("/", sc.RenderRoot) web.Get("/query\\.?(.*)", zcc.Query) web.Post("/query\\.?(.*)", zcc.Query) web.Get("/distribution\\.?(.*)", zcc.GetDistribution) web.Post("/distribution\\.?(.*)", zcc.GetDistribution) web.Get("/countries\\.?(.*)", zcc.GetCountries) web.Post("/countries\\.?(.*)", zcc.GetCountries) web.Get("/map_(\\d*)\\.png", pc.RenderImage) web.Get("/distmap_(\\d*)\\.png", pc.RenderDistributionImage) web.Get("/images/(.*)", sc.RenderImages) web.Get("/js/(.*)", sc.RenderJS) web.Get("/(.*)", sc.RenderHTML) fmt.Printf("Server started on port %v in %v\n", port, time.Since(start)) web.Run("0.0.0.0:" + port) }
func AttachAdmin(url string) { // auth web.Get(url+"login/", login) web.Post(url+"login/", login) web.Get(url+"logout/", logout) // users /* too much unnecessary work? web.Get(url + "users/", userList) web.Get(url + "users/edit/(.*)", userEdit) web.Get(url + "users/delete/(.*)", userDelete) web.Get(url + "users/add/", userAdd) web.Post(url + "users/add/", userAddPost) */ web.Get(url, adminIndex) }
func generateResourceRoutes(resource controllers.Controllers) { resourceString := controllers.FriendlyName(resource) models.SetupTable(resourceString) log.Printf(" - starting /%s routes generation\n", resourceString) web.Get("(?i)/"+resourceString+"/?", resource.Index) web.Get("(?i)/"+resourceString+"/(\\d*)", resource.Show) web.Get("(?i)/"+resourceString+"/new/?", resource.New) web.Get("(?i)/"+resourceString+"/(\\d*)", resource.Edit) web.Post("(?i)/"+resourceString+"/?", resource.Create) web.Put("(?i)/"+resourceString+"/(\\d*)", resource.Update) web.Delete("(?i)/"+resourceString+"/(\\d*)", resource.Delete) log.Printf(" - finished /%s routes generation\n", resourceString) }
func (mod *WebBee) Run(cin chan bees.Event) { mod.eventChan = cin web.Get(mod.path, mod.GetRequest) web.Post(mod.path, mod.PostRequest) web.Run(mod.addr) for { select { case <-mod.SigChan: web.Close() return default: } } }
func main() { rand.Seed(time.Now().UnixNano()) web.Config.CookieSecret = "7C19QRmwf3mHZ9CPAaPQ0hsWeufKd" web.Get("/", func(ctx *web.Context) string { ctx.Redirect(302, "/said") return "" }) web.Get("/said", func() string { return form }) web.Post("/say", func(ctx *web.Context) string { uid := fmt.Sprintf("%d\n", rand.Int63()) ctx.SetSecureCookie("user", uid, 3600) users[uid] = ctx.Params["said"] return `<a href="/final">Click Here</a>` }) web.Get("/final", func(ctx *web.Context) string { uid, _ := ctx.GetSecureCookie("user") return "You said " + users[uid] }) web.Run("0.0.0.0:9999") }
func startUp() { //Create DB if it doesn't exist if !exists("./sqlite.db") { success := createDB() if !success { panic("Fatal Error, DB could not be created") } } //Create Files/ if it doesn't exist if !exists("./files/") { os.Mkdir("files/", 0766) } updateURL := make(chan *urlUpdateMsg) go handleDB(updateURL) //Set route handlers web.Post("/api/upload", func(ctx *web.Context) string { return handleUpload(ctx, updateURL) }) web.Get("/([a-z0-9]{6}.?[a-z0-9]*)", getFile) }
func (s HTTPServer) Run(proto string) { logger := initLogger(Settings.Log.File) redis := &redis.Client{Addr: Settings.Redis.Addr(), Db: Settings.Redis.DB, Password: Settings.Redis.Password} var ( indexHandler = &IndexHandler{} restHandler = &RestQueueHandler{redis, logger} wsHandler = &WSQueueHandler{redis, logger} ) web.Get("/", indexHandler.Get) web.Get("/q", restHandler.List) web.Get("/q/(.+)", restHandler.Get) web.Post("/q/(.+)", restHandler.Put) web.Delete("/q/(.+)", restHandler.Clear) web.Get("/ws/(.+)", wsHandler.Consumer) web.SetLogger(logger) addr := Settings.HTTPServer.Addr() switch proto { case "http": web.Run(addr) case "fcgi": web.RunFcgi(addr) case "scgi": web.RunScgi(addr) default: flag.Usage() os.Exit(1) } }
func main() { web.Get("/", index) web.Post("/process", process) web.Run("0.0.0.0:9999") }
func main() { web.Get("/", index) web.Post("/multipart", multipart) web.Run("0.0.0.0:9999") }
func routes() { web.Put("/", paste) //Defined in paste.go web.Post("/", paste) //Defined in paste.go web.Get("/([a-zA-Z0-9]+)", getPaste) web.Get("/", index) }
func main() { rootDir := filepath.Dir(os.Args[0]) env := os.Getenv("ISUCON_ENV") if env == "" { env = "local" } configFile := filepath.Clean(rootDir + fmt.Sprintf("/../config/common.%s.json", env)) f, err := ioutil.ReadFile(configFile) if err != nil { log.Fatal(err.Error()) } var config Config json.Unmarshal(f, &config) templateFile := filepath.Join(rootDir, "templates", "*.t") tp, err := template.ParseGlob(templateFile) if err != nil { log.Fatal(err.Error()) } db, err = sql.Open("mysql", fmt.Sprintf( "%v:%v@tcp(%v:%v)/%s?charset=utf8", config.Database.Username, config.Database.Password, config.Database.Host, config.Database.Port, config.Database.DBName)) if err != nil { log.Fatal(err.Error()) } web.Get("/", func(ctx *web.Context) { if err := tp.ExecuteTemplate(ctx, "index", &struct { RecentSolds []RecentSold Artists []Artist }{recentSolds(), artists()}); err != nil { log.Print(err.Error()) ctx.Abort(500, "Server Error") } }) web.Get("/artist/(.*)", func(ctx *web.Context, id string) { a := artist(id) if err := tp.ExecuteTemplate(ctx, "artist", &struct { RecentSolds []RecentSold Name string Tickets []Ticket }{recentSolds(), a.Name, tickets(id)}); err != nil { log.Print(err.Error()) ctx.Abort(500, "Server Error") } }) web.Get("/ticket/(.*)", func(ctx *web.Context, id string) { t, v := ticket(id) if err := tp.ExecuteTemplate(ctx, "ticket", &struct { RecentSolds []RecentSold Ticket Ticket Variations []Variation }{recentSolds(), *t, v}); err != nil { log.Print(err.Error()) ctx.Abort(500, "Server Error") } }) web.Post("/buy", func(ctx *web.Context) { variationId, ok := ctx.Params["variation_id"] if !ok { variationId = "" } memberId, ok := ctx.Params["memberId"] if !ok { memberId = "" } tx, err := db.Begin() if err != nil { log.Print(err.Error()) ctx.Abort(500, "Server Error") } res, err := tx.Exec(`INSERT INTO order_request (member_id) VALUES (?)`, memberId) if err != nil { log.Print(err.Error()) ctx.Abort(500, "Server Error") } orderId, err := res.LastInsertId() if err != nil { log.Print(err.Error()) ctx.Abort(500, "Server Error") } res, err = tx.Exec(`UPDATE stock SET order_id = ? WHERE variation_id = ? AND order_id IS NULL ORDER BY RAND() LIMIT 1`, orderId, variationId) if err != nil { log.Print(err.Error()) ctx.Abort(500, "Server Error") } affected, err := res.RowsAffected() if err != nil { log.Print(err.Error()) ctx.Abort(500, "Server Error") } if affected > 0 { rows, err := tx.Query(`SELECT seat_id FROM stock WHERE order_id = ? LIMIT 1`, orderId) if err != nil { tx.Rollback() log.Print(err.Error()) ctx.Abort(500, "Server Error") } var seatId string if rows.Next() { rows.Scan(&seatId) } rows.Close() tx.Commit() err = tp.ExecuteTemplate(ctx, "complete", &struct { SeatId string MemberId string }{ seatId, memberId, }) } else { tx.Rollback() err = tp.ExecuteTemplate(ctx, "soldout", nil) } if err != nil { log.Print(err.Error()) ctx.Abort(500, "Server Error") } }) web.Get("/admin", func(ctx *web.Context) { err := tp.ExecuteTemplate(ctx, "admin", nil) if err != nil { log.Print(err.Error()) ctx.Abort(500, "Server Error") } }) web.Post("/admin", func(ctx *web.Context) { sqlFile := filepath.Clean(filepath.Join(rootDir, "../config/database/initial_data.sql")) f, err := os.Open(sqlFile) if err != nil { log.Print(err.Error()) ctx.Abort(500, "Server Error") } defer f.Close() buf := bufio.NewReader(f) for { b, err := buf.ReadString('\n') if err != nil { break } else if line := strings.TrimSpace(string(b)); line != "" { _, err = db.Exec(line) if err != nil { log.Print(err.Error()) ctx.Abort(500, "Server Error") } } } ctx.Redirect(302, "/admin") }) web.Get("/admin/order.csv", func(ctx *web.Context) { rows, err := db.Query(` SELECT order_request.*, stock.seat_id, stock.variation_id, stock.updated_at FROM order_request JOIN stock ON order_request.id = stock.order_id ORDER BY order_request.id ASC `) if err != nil { log.Print(err.Error()) ctx.Abort(500, "Server Error") } defer rows.Close() for rows.Next() { var id, memberId, seatId, variationId, updatedAt string rows.Scan(&id, &memberId, &seatId, &variationId, &updatedAt) ctx.SetHeader("Content-Type", "text/csv; charset=utf-8", true) line := strings.Join([]string{id, memberId, seatId, variationId, updatedAt}, ",") + "\n" ctx.Write([]byte(line)) } }) web.Config.StaticDir = filepath.Clean(rootDir + "/../staticfiles") web.Run(":8081") }
func main() { web.Get("/(.*)", getItem) web.Post("/(.*)", upsertItem) web.Delete("/(.*)", deleteItem) web.Run(flagPort) }
func main() { log.Print("Starting GLDB server") var db, err = gldb.GLDBFromMongoURL(os.Getenv("GLDB_MONGO_URL")) if err != nil { panic(err) } log.Print("Connected to mongolab") // data collection web.Post("/did", func(c *web.Context) string { r := &gldb.Review{ DoableURL: c.Params["what"], Comment: c.Params["comment"], QualitiesConfirmed: strings.Split(c.Params["qualities"], ","), } scrapeResults, err := scraper.Slurp(r.DoableURL) if err != nil { panic(err) } db.AddReviewAndRelatedData(r, c.Params["metro"], c.Params["sociographic"], c.Params["comment"], scrapeResults) return "thanks" }) // querying web.Get("/subjects", func(c *web.Context) string { c.ContentType("json") interests := db.SubjectsInMetro(c.Params["metro"], c.Params["quality"]) body, err := json.MarshalIndent(interests, "", " ") if err != nil { panic(err) } return string(body) }) web.Get("/subject", func(c *web.Context) string { c.ContentType("json") doables := db.DoablesForSubjectInMetro(c.Params["metro"], c.Params["subject"]) body, err := json.MarshalIndent(doables, "", " ") if err != nil { panic(err) } return string(body) }) // debugging web.Get("/raw", func(c *web.Context) string { f := scraper.NewFetcherForURL(c.Params["url"]) return string(*f.ResponseBodyBytes()) }) web.Get("/json", func(c *web.Context) string { c.ContentType("json") results, err := scraper.Slurp(c.Params["url"]) if err != nil { panic(err) } body, err := json.MarshalIndent(results, "", " ") if err != nil { panic(err) } return string(body) }) web.Run("0.0.0.0:" + os.Getenv("PORT")) }