// Creates and returns a new Manager. func New() *Manager { refreshChannel := make(chan string, 10) quitChannel := make(chan int) refreshCounter := prometheus.NewCounterVec(prometheus.CounterOpts{ Namespace: "proxym", Subsystem: "refresh", Name: "count", Help: "Number of refreshes triggered", }, []string{"result"}) prometheus.MustRegister(refreshCounter) var c Config envconfig.Process("proxym", &c) m := &Manager{ Config: &c, httpRouter: pat.New(), refresh: refreshChannel, refreshCounter: refreshCounter, quit: quitChannel, } m.httpRouter.Get("/metrics", prometheus.Handler()) return m }
func main() { store = sessions.NewCookieStore([]byte("this-is-super-secret")) // securecookie.GenerateRandomKey(32), // securecookie.GenerateRandomKey(32)) store.Options.HttpOnly = true store.Options.Secure = true clients = make(map[string]*imap.Client) m := pat.New() m.Get("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) m.Get("/login", handler(LoginForm)) m.Post("/login", handler(LoginHandler)) m.Get("/logout", handler(Logout)) m.Get("/mail", handler(InboxHandler)) m.Get("/mail/messages/", handler(MessagesHandler)) m.Get("/mail/message/:id", handler(MessageHandler)) m.Get("/mail/attachment/:msg/:id", handler(AttachmentHandler)) m.Post("/mail/archive/:id", handler(ArchiveHandler)) m.Post("/mail/delete/:id", handler(DeleteHandler)) m.Get("/", handler(root)) http.Handle("/", m) http.ListenAndServeTLS(":5000", "certs/newcert.pem", "certs/privkey.pem", nil) }
// Setup routes for serving dynamic content func setupHandlers() { m := pat.New() api.AddHandlers(m, "/api") m.Get("/movies", handler.ErrorHandler(handler.MovieList)) m.Get("/movies/:id", handler.ErrorHandler(handler.MovieShow)) m.Get("/movies/:id/video", http.HandlerFunc(handler.MoviePlay)) m.Get("/movies/:id/transcode", http.HandlerFunc(handler.MovieTranscode)) m.Get("/videos/", http.StripPrefix("/videos/", http.FileServer(http.Dir("/tmp/videos")))) m.Get("/libraries", handler.ErrorHandler(handler.LibraryList)) m.Post("/libraries", handler.ErrorHandler(handler.LibraryCreate)) m.Get("/libraries/:id/process", handler.ErrorHandler(handler.LibraryProcess)) m.Get("/series", handler.ErrorHandler(handler.SeriesList)) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // standard header variables that should be set, for good measure. w.Header().Add("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate") w.Header().Add("X-Frame-Options", "DENY") w.Header().Add("X-Content-Type-Options", "nosniff") w.Header().Add("X-XSS-Protection", "1; mode=block") m.ServeHTTP(w, r) }) }
func Run(conf Config) (http.Handler, error) { var err error db, err = thunder.Open(conf.DB, 0600, thunder.Options{ KeyCodec: stringc.Codec(), ValueCodec: jsonc.Codec(), }) if err != nil { return nil, err } err = initDB(db) if err != nil { return nil, err } router := pat.New() router.Post("/todos/:list/:title", http.HandlerFunc(updateTodo)) router.Get("/todos/:list/", http.HandlerFunc(todos)) router.Post("/todos/:list/", http.HandlerFunc(newTodo)) router.Get("/todos/", http.HandlerFunc(lists)) router.Post("/todos/", http.HandlerFunc(newList)) return router, nil }
func HTTPServe() { restfulAPIServer := pat.New() handlers := map[string]map[string]func(*Request) (int, interface{}){ "GET": { "/profile/": profile, "/version/": version, "/api/app/list/": listEruApps, }, "POST": { "/api/container/add/": addNewContainer, "/api/container/:container_id/addvlan/": addVlanForContainer, "/api/container/:container_id/setroute/": setRouteForContainer, }, } for method, routes := range handlers { for route, handler := range routes { restfulAPIServer.Add(method, route, http.HandlerFunc(JSONWrapper(handler))) } } http.Handle("/", restfulAPIServer) logs.Info("API http server start at", g.Config.API.Addr) err := http.ListenAndServe(g.Config.API.Addr, nil) if err != nil { logs.Assert(err, "ListenAndServe: ") } }
func newServer() *http.Server { n := negroni.New() // Middlewares if Settings["environments"].GetBool("log") { n.Use(negroni.NewLogger()) } n.UseFunc(recovery()) n.Use(negroni.NewStatic(http.Dir("./public"))) // Setup routes router := pat.New() router.Get("/api/v1/:env/driver/:ID", http.HandlerFunc(getDriverLocation)) //router.Post("/api/v1/<resource>", http.HandlerFunc(/*handle func*/)) // Add alive endpoint // router.Get("/alive", http.HandlerFunc(alive)) // Add the router action n.UseHandler(router) Server := &http.Server{ Addr: ":" + Settings["environments"].GetString("server.port"), Handler: n, ReadTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second, MaxHeaderBytes: 1 << 20, } return Server }
func main() { // if err := GConf.FromJSON(*Configfile); err != nil { log.Println("parse config file error: ", err) os.Exit(1) } CoreCnt, err := strconv.Atoi(GConf.CoreCnt) if err == nil { if CoreCnt > 0 { runtime.GOMAXPROCS(CoreCnt) } } logFile, err := os.OpenFile(GConf.LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) // if err != nil { log.Fatal(fmt.Sprintf("Log file error: %s", GConf.LogFile), err) return } defer logFile.Close() log.SetOutput(logFile) debug(dump(GConf)) //set global compiled regex GRatRegex, err = regexp.Compile(fmt.Sprintf("^[A-Za-z0-9_]{%s}$", GConf.KeySize)) if err != nil { log.Fatal("Can not compile reg expresion: ", err) } //set redispool GRedisPool = &redis.Pool{ MaxIdle: 3, MaxActive: 10, // max number of connections Dial: func() (redis.Conn, error) { c, err := redis.Dial("tcp", GConf.RedisHost+":"+GConf.RedisPort) if err != nil { log.Fatal("Can not create Redis pool: ", err) } return c, err }, } mux := pat.New() mux.Get("/r/:id", http.HandlerFunc(ratHandle)) mux.Get("/health", http.HandlerFunc(healthHandle)) http.Handle("/", mux) log.Println("Listening " + GConf.HttpHost + ":" + GConf.HttpPort) err = http.ListenAndServe(GConf.HttpHost+":"+GConf.HttpPort, nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
func New(cfg *config.Config) (http.Handler, error) { srv := &server{config: cfg, bk: make(map[string]*backend.Backend)} srv.loadTemplates() for _, bk := range srv.config.Backends { srv.bk[bk.Id] = backend.New(&bk) } m := pat.New() m.Add("GET", "/", http.HandlerFunc(srv.ServeRoot)) m.Add("GET", "/search/", http.HandlerFunc(srv.ServeSearch)) m.Add("GET", "/search/:backend", http.HandlerFunc(srv.ServeSearch)) m.Add("GET", "/about", http.HandlerFunc(srv.ServeAbout)) m.Add("GET", "/opensearch.xml", http.HandlerFunc(srv.ServeOpensearch)) m.Add("GET", "/api/v1/search/", http.HandlerFunc(srv.ServeAPISearch)) m.Add("GET", "/api/v1/search/:backend", http.HandlerFunc(srv.ServeAPISearch)) mux := http.NewServeMux() mux.Handle("/assets/", http.FileServer(http.Dir(path.Join(cfg.DocRoot, "htdocs")))) mux.Handle("/socket", websocket.Handler(srv.HandleWebsocket)) mux.Handle("/", m) srv.inner = &requestLogger{mux} return srv, nil }
func StartEndpoint(port string, store *Store) *Endpoint { endpoint := Endpoint{store: store} mux := pat.New() mux.Post(fmt.Sprintf("/:topic"), http.HandlerFunc(endpoint.PostEvent)) go http.ListenAndServe("127.0.0.1:"+port, mux) return &endpoint }
func main() { initSQL() mware.SetGetDBConnectionFunc(db) m := pat.New() // no auth routes m.Get(prefix+"/community", mware.CommunityHandler()) m.Post(prefix+"/login", mware.LoginHandler()) m.Post(prefix+"/logout", mware.LogoutHandler()) m.Post(prefix+"/signup", mware.SignupHandler()) m.Post(prefix+"/reset-password", mware.ResetPasswordHandler()) // m.Post(prefix+"/request-invite", mware.RequestInviteHandler()) m.Get(prefix+"/members", mware.GetAll(&model.Member{})) m.Get(prefix+"/members/:id", mware.GetByID(&model.Member{})) m.Get(prefix+"/feeds", mware.GetAll(&model.Feed{})) m.Get(prefix+"/feeds/:id", mware.GetByID(&model.Feed{})) m.Get(prefix+"/categories", mware.GetAll(&model.Category{})) m.Get(prefix+"/categories/:id", mware.GetByID(&model.Category{})) m.Get(prefix+"/top-stories", mware.TopStoriesHandler()) m.Get(prefix+"/stories", mware.GetAll(&model.Story{})) m.Get(prefix+"/stories/:id", mware.GetByID(&model.Story{})) // auth routes m.Post(prefix+"/invite", mware.Auth(mware.InviteHandler())) m.Post(prefix+"/change-password", mware.Auth(mware.ChangePasswordHandler())) m.Post(prefix+"/members", mware.Auth(mware.Create(&model.Member{}))) m.Put(prefix+"/members/:id", mware.Auth(mware.UpdateByID(&model.Member{}))) m.Del(prefix+"/members/:id", mware.Auth(mware.DeleteByID(&model.Member{}))) m.Post(prefix+"/feeds", mware.Auth(mware.Create(&model.Feed{}))) m.Put(prefix+"/feeds/:id", mware.Auth(mware.UpdateByID(&model.Feed{}))) m.Del(prefix+"/feeds/:id", mware.Auth(mware.DeleteByID(&model.Feed{}))) m.Post(prefix+"/categories", mware.Auth(mware.Create(&model.Category{}))) m.Put(prefix+"/categories/:id", mware.Auth(mware.UpdateByID(&model.Category{}))) m.Del(prefix+"/categories/:id", mware.Auth(mware.DeleteByID(&model.Category{}))) m.Del(prefix+"/stories/:id", mware.Auth(mware.DeleteByID(&model.Story{}))) // cors m.Options(prefix+"/:any", mware.CommunityHandler()) m.Options(prefix+"/:any1/:any2", mware.CommunityHandler()) go runInBackground(time.Minute*10, model.ListenToFeeds) go runInBackground(time.Minute*5, model.DecayScores) http.Handle("/", m) log.Println("Listening...") if err := http.ListenAndServe(":8080", nil); err != nil { panic(err) } }
func init() { blog_config, err := config.ReadJsonFile("blarg_config.json") if err != nil { panic(err) } root := config.Stringify(blog_config["blog_root"]) // test for default m := pat.New() handle_method := func(method string, urlpattern string, handler http.HandlerFunc) { m.Add(method, root+urlpattern, handler) } handle := func(urlpattern string, handler http.HandlerFunc) { m.Get(root+urlpattern, handler) } handle("list/:page/:invalid", http.NotFound) handle("list/:page", layout.IndexPageHandler(blog_config, "list")) handle("list/", layout.IndexListHandler(blog_config, "list")) handle("index/", layout.IndexListHandler(blog_config, "list")) handle("article/:name/:invalid", http.NotFound) handle("article/:name", layout.GetArticle(blog_config, "article")) handle("article/", http.NotFound) handle("label/:label/:page/:invalid", http.NotFound) handle("label/:label/:page", layout.LabelPage(blog_config, "label")) handle("label/:label", layout.LabelList(blog_config, "label")) handle("label/", http.NotFound) handle("admin/edit/:name/:invalid", http.NotFound) handle("admin/edit/:name", layout.EditPost(blog_config)) handle("admin/edit/", layout.EditPost(blog_config)) handle("admin/dump/all.json/:invalid", http.NotFound) handle("admin/dump/all.json", layout.JSONAllEntries(blog_config)) handle("admin/dump/:invalid", http.NotFound) handle("admin/gettext/:name/:invalid", http.NotFound) handle("admin/gettext/:name", layout.GetPostText(blog_config)) handle_method("POST", "admin/render/:invalid", http.NotFound) handle_method("POST", "admin/render/", layout.RenderPost(blog_config)) // pat seems to interfere with the blobstore's MIME parsing http.HandleFunc(root+"admin/post", layout.Save(blog_config)) handle("sitemap.xml", layout.GetSitemap(blog_config)) m.Get("/index.rss", http.HandlerFunc(layout.GetRSS(blog_config))) // matching on / will match all URLs // so you have to catch invalid top-level URLs first handle(":invalid/", http.NotFound) handle("", layout.IndexListHandler(blog_config, "list")) http.Handle(root, m) }
func main() { // 静态资源目录 assetsDir = "./public/" m := pat.New() m.Get("/", http.HandlerFunc(HelloController)) m.Get("/assets/:file", http.HandlerFunc(AssetsServer)) m.Get("/about", http.HandlerFunc(AboutController)) m.Get("/contact", http.HandlerFunc(ContactController)) // Register this pat with the default serve mux so that other packages // may also be exported. (i.e. /debug/pprof/*) http.Handle("/", m) // 非生产环境http使用7000端口 if os.Getenv("PI_ENV") != "production" { listenPort = 7000 } var fullListenParam string = fmt.Sprintf(":%d", listenPort) err := http.ListenAndServe(fullListenParam, nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
func NewServer(cfg *Config) (*Server, error) { concfg := consul.DefaultConfig() con, err := consul.NewClient(concfg) if err != nil { return nil, err } if cfg.key == nil { return nil, fmt.Errorf("Config needs to contain a key") } s := &Server{ cfg: cfg, mux: pat.New(), con: con, } s.mux.Post("/create", http.HandlerFunc(s.create)) s.mux.Post("/token", s.extractOrg(http.HandlerFunc(s.newToken))) s.mux.Post("/update/:id", http.HandlerFunc(s.update)) s.mux.Post("/dir/:type/_scoped", s.extractOrg(http.HandlerFunc(s.updateToken))) s.mux.Post("/dir/:type/:id", s.extractOrg(http.HandlerFunc(s.set))) s.mux.Post("/dir/:type", s.extractOrg(http.HandlerFunc(s.setGenId))) s.mux.Get("/dir/:type/_search", s.extractOrg(http.HandlerFunc(s.search))) s.mux.Get("/dir/:type/:id", s.extractOrg(http.HandlerFunc(s.get))) return s, nil }
func registerRoutes() http.Handler { h := http.NewServeMux() mux := pat.New() // register routes mux.Get("/", http.HandlerFunc(root)) mux.Get("/upload", oauthWrapper(http.HandlerFunc(uploadPage))) mux.Post("/upload", oauthWrapper(http.HandlerFunc(uploadHandler))) mux.Get("/auth", http.HandlerFunc(oauthRedirectHandler)) mux.Get("/search", http.HandlerFunc(searchPage)) mux.Get("/image/:hash", http.HandlerFunc(imagePage)) mux.Get("/:hash", http.HandlerFunc(getImageHandler)) mux.Get("/:hash/:width", http.HandlerFunc(getImageHandlerWidth)) mux.Get("/", http.HandlerFunc(root)) h.Handle("/", loggerMiddlerware(mux)) h.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static/")))) // load templates templates = loadTemplates() return context.ClearHandler(h) }
func RegisterRoutes() *pat.PatternServeMux { m := pat.New() // API // Auth m.Post("/api/auth/sessions", http.HandlerFunc(PostSessions)) // TODO: Is this the best route? m.Del("/api/auth/sessions/:token", http.HandlerFunc(DeleteSessions)) // Users m.Post("/api/users", http.HandlerFunc(PostUser)) m.Get("/api/users/:id", http.HandlerFunc(GetUser)) m.Put("/api/users/:id", http.HandlerFunc(PutUsers)) m.Del("/api/users/:id", http.HandlerFunc(DeleteUser)) // Preferences m.Get("/api/preferences", http.HandlerFunc(GetPreferences)) m.Put("/api/preferences", http.HandlerFunc(PutPreferences)) // Subscriptions m.Post("/api/subscriptions", http.HandlerFunc(PostSubscription)) m.Get("/api/subscriptions", http.HandlerFunc(GetSubscriptions)) m.Del("/api/subscriptions/:id", http.HandlerFunc(DeleteSubscription)) // Articles m.Get("/api/subscriptions/articles", http.HandlerFunc(GetAllArticles)) m.Get("/api/subscriptions/:id/articles", http.HandlerFunc(GetArticles)) m.Put("/api/subscriptions/:subid/articles/:artid", http.HandlerFunc(PutArticle)) // Favorites m.Post("/api/favorites", http.HandlerFunc(PostFavorites)) m.Get("/api/favorites", http.HandlerFunc(GetFavorites)) m.Del("/api/favorites/:id", http.HandlerFunc(DeleteFavorite)) // First time setup m.Get("/api/setup", http.HandlerFunc(GetSetup)) // TODO: Is this really the best URL for this? return m }
func agentCommandFunc(c *cli.Context) { mux := pat.New() mux.Post("/containers", http.HandlerFunc(handler.ContainerCreate)) mux.Put("/containers/:container_id", http.HandlerFunc(handler.ContainerUpdate)) mux.Del("/containers/:container_id", http.HandlerFunc(handler.ContainerDelete)) mux.Get("/containers", http.HandlerFunc(handler.ContainersIndex)) mux.Post("/portbindings", http.HandlerFunc(handler.PortBindingCreate)) mux.Get("/portbindings", http.HandlerFunc(handler.PortBindingsIndex)) mux.Del("/portbindings/:port", http.HandlerFunc(handler.PortBindingDelete)) mux.Get("/hosts", http.HandlerFunc(handler.HostsIndex)) mux.Get("/host", http.HandlerFunc(handler.HostShow)) http.Handle("/", mux) currentHost, err := host.New( c.String("hostname"), c.String("external_interface"), c.String("internal_interface"), c.String("external_ip"), c.String("internal_ip"), ) if err != nil { log.Printf("Error getting host information: %v\n", err) os.Exit(1) } err = currentHost.Persist() if err != nil { log.Printf("Error persisting host information: %v\n", err) os.Exit(1) } log.Println("Listening on port 2728") http.ListenAndServe(":2728", nil) }
// NewHandler creates a routed tus protocol handler. This is the simplest // way to use tusd but may not be as configurable as you require. If you are // integrating this into an existing app you may like to use tusd.NewUnroutedHandler // instead. Using tusd.NewUnroutedHandler allows the tus handlers to be combined into // your existing router (aka mux) directly. It also allows the GET and DELETE // endpoints to be customized. These are not part of the protocol so can be // changed depending on your needs. func NewHandler(config Config) (*Handler, error) { if err := config.validate(); err != nil { return nil, err } handler, err := NewUnroutedHandler(config) if err != nil { return nil, err } routedHandler := &Handler{ UnroutedHandler: handler, } mux := pat.New() routedHandler.Handler = handler.Middleware(mux) mux.Post("", http.HandlerFunc(handler.PostFile)) mux.Head(":id", http.HandlerFunc(handler.HeadFile)) mux.Add("PATCH", ":id", http.HandlerFunc(handler.PatchFile)) // Only attach the DELETE handler if the Terminate() method is provided if config.StoreComposer.UsesTerminater { mux.Del(":id", http.HandlerFunc(handler.DelFile)) } // GET handler requires the GetReader() method if config.StoreComposer.UsesGetReader { mux.Get(":id", http.HandlerFunc(handler.GetFile)) } return routedHandler, nil }
func NewHTTPService(port string, reg Storage) *HTTPService { h := &HTTPService{ Address: port, Registry: reg, mux: pat.New(), defaultLease: 5 * time.Minute, inflight: make(map[MessageId]*inflightDelivery), background: make(chan struct{}, 3), done: make(chan struct{}), } h.mux.Post("/mailbox/:name", http.HandlerFunc(h.declare)) h.mux.Add("DELETE", "/mailbox/:name", http.HandlerFunc(h.abandon)) h.mux.Put("/mailbox/:name", http.HandlerFunc(h.push)) h.mux.Get("/mailbox/:name", http.HandlerFunc(h.poll)) h.mux.Add("DELETE", "/message/:id", http.HandlerFunc(h.ack)) h.mux.Put("/message/:id", http.HandlerFunc(h.nack)) s := &http.Server{ Addr: port, Handler: h.mux, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } h.server = s return h }
func main() { // err := 0; // database connection var err error db, err = sql.Open("mysql", "root:root@tcp([127.0.0.1]:3306)/dbapi?autocommit=true&charset=utf8") if err != nil { fmt.Println("error conecting to DB") } else { fmt.Println("connected") } defer db.Close() // connection pool db.SetMaxIdleConns(100) err = db.Ping() // This DOES open a connection if necessary. This makes sure the database is accessible if err != nil { log.Fatalf("Error on opening database connection: %s", err.Error()) } mux := pat.New() mux.Get("/mysql/:name/:id", http.HandlerFunc(profile)) http.Handle("/", mux) log.Println("Listening port:3000 ") http.ListenAndServe(":3000", nil) }
func main() { ret := pat.New() ret.Get("/", http.HandlerFunc(index)) ret.Post("/add", http.HandlerFunc(add)) ret.Del("/del/:id", http.HandlerFunc(del)) http.ListenAndServe(":8080", ret) }
func main() { log.SetFlags(log.Lshortfile) db = initdb() if len(os.Args) == 2 && os.Args[1] == "gen" { gen() return } m := pat.New() m.Put("/:cmd-:ver-:plat", authenticate{herokaiOnly{http.HandlerFunc(put)}}) m.Post("/:cmd-:plat", authenticate{herokaiOnly{http.HandlerFunc(setcur)}}) m.Get("/:cmd-:ver-:plat.gz", http.HandlerFunc(full)) m.Get("/:cmd-:oldver-next-:plat.hkdiff", http.HandlerFunc(patch)) m.Get("/:plat/:oldver/next.hkdiff", http.HandlerFunc(patch)) // for compat m.Get("/:plat/:cmd.gz", http.HandlerFunc(full)) m.Get("/hk.gz", http.HandlerFunc(full)) // for the html page m.Get("/release.txt", http.HandlerFunc(lsrelease)) m.Get("/cur.txt", http.HandlerFunc(lscur)) m.Get("/patch.txt", http.HandlerFunc(lspatch)) m.Get("/next.txt", http.HandlerFunc(lsnext)) m.Get("/", http.FileServer(http.Dir("hkdist/public"))) var root http.Handler = m if os.Getenv("HTTPSONLY") != "" { root = httpsOnly{m} } http.Handle("/", root) err := http.ListenAndServe(":"+os.Getenv("PORT"), nil) if err != nil { log.Fatalf(`{"func":"ListenAndServe", "error":%q}`, err) } }
func main() { dbMan, err := db.NewPostgresDBManager() cpus := runtime.NumCPU() runtime.GOMAXPROCS(cpus) WorkerPool.Run() go processResults(dbMan) go func() { sigCh := make(chan os.Signal) signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT) // Wait for a signal sig := <-sigCh log.Print("Signal received. Shutting down.", sig) WorkerPool.Add(func(args ...interface{}) interface{} { WorkerPool.Stop() return nil }, "kill") }() if err != nil { log.Fatal(err) } else { mux := pat.New() http.Handle("/", mux) mux.Get("/hello", Hello(dbMan)) mux.Post("/feed", AddFeed(dbMan)) mux.Get("/feed/:id", GetFeedByID(dbMan)) http.ListenAndServe(":"+os.Getenv("PORT"), nil) } }
func main() { // middleware middle := interpose.New() middle.Use(adaptors.FromNegroni(cors.New(cors.Options{ // CORS AllowedOrigins: []string{"*"}, }))) // router router := pat.New() middle.UseHandler(router) router.Get("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { url := r.URL.Query().Get("url") if url != "" { encoded := imgbase64.FromRemote(url) fmt.Fprint(w, encoded) } else { fmt.Fprint(w, "/?url=<your-image-url> returns the base64 data-URI of that image.") } })) // listen port := os.Getenv("PORT") if port == "" { port = "5000" } log.Print("listening...") http.ListenAndServe(":"+port, middle) }
// start starts the api using the start function // sets on the API on initialization. func (a *api) Start() { a.server = pat.New() commandRoute := "/commands/:command" deviceCommandRoute := "/robots/:robot/devices/:device/commands/:command" robotCommandRoute := "/robots/:robot/commands/:command" a.server.Get("/", a.setHeaders(a.root)) a.server.Get("/commands", a.setHeaders(a.commands)) a.server.Get(commandRoute, a.setHeaders(a.executeCommand)) a.server.Post(commandRoute, a.setHeaders(a.executeCommand)) a.server.Get("/robots", a.setHeaders(a.robots)) a.server.Get("/robots/:robot", a.setHeaders(a.robot)) a.server.Get("/robots/:robot/commands", a.setHeaders(a.robotCommands)) a.server.Get(robotCommandRoute, a.setHeaders(a.executeRobotCommand)) a.server.Post(robotCommandRoute, a.setHeaders(a.executeRobotCommand)) a.server.Get("/robots/:robot/devices", a.setHeaders(a.robotDevices)) a.server.Get("/robots/:robot/devices/:device", a.setHeaders(a.robotDevice)) a.server.Get("/robots/:robot/devices/:device/commands", a.setHeaders(a.robotDeviceCommands)) a.server.Get(deviceCommandRoute, a.setHeaders(a.executeDeviceCommand)) a.server.Post(deviceCommandRoute, a.setHeaders(a.executeDeviceCommand)) a.server.Get("/robots/:robot/connections", a.setHeaders(a.robotConnections)) a.server.Get("/robots/:robot/connections/:connection", a.setHeaders(a.robotConnection)) a.server.Get("/:a", a.setHeaders(a.robeaux)) a.server.Get("/:a/", a.setHeaders(a.robeaux)) a.server.Get("/:a/:b", a.setHeaders(a.robeaux)) a.server.Get("/:a/:b/", a.setHeaders(a.robeaux)) a.server.Get("/:a/:b/:c", a.setHeaders(a.robeaux)) a.server.Get("/:a/:b/:c/", a.setHeaders(a.robeaux)) a.start(a) }
func main() { dry := flag.Bool("dry", false, "dry-run: does not start the server (for testing purpose)") configFile := flag.String("config", "/etc/gandalf.conf", "Gandalf configuration file") flag.Parse() err := config.ReadAndWatchConfigFile(*configFile) if err != nil { msg := `Could not find gandalf config file. Searched on %s. For an example conf check gandalf/etc/gandalf.conf file.\n %s` log.Panicf(msg, *configFile, err) } db.Connect() router := pat.New() router.Post("/user/:name/key", http.HandlerFunc(api.AddKey)) router.Del("/user/:name/key/:keyname", http.HandlerFunc(api.RemoveKey)) router.Get("/user/:name/keys", http.HandlerFunc(api.ListKeys)) router.Post("/user", http.HandlerFunc(api.NewUser)) router.Del("/user/:name", http.HandlerFunc(api.RemoveUser)) router.Post("/repository", http.HandlerFunc(api.NewRepository)) router.Post("/repository/grant", http.HandlerFunc(api.GrantAccess)) router.Del("/repository/revoke", http.HandlerFunc(api.RevokeAccess)) router.Del("/repository/:name", http.HandlerFunc(api.RemoveRepository)) router.Get("/repository/:name", http.HandlerFunc(api.GetRepository)) router.Put("/repository/:name", http.HandlerFunc(api.RenameRepository)) port, err := config.GetString("webserver:port") if err != nil { panic(err) } if !*dry { log.Fatal(http.ListenAndServe(port, router)) } }
func main() { listen := os.Getenv("COMIC_LISTEN") user := []byte(os.Getenv("COMIC_USER")) pass := []byte(os.Getenv("COMIC_PASSWD")) router := pat.New() router.Get("/", http.HandlerFunc(views.LastComicView)) router.Get("/first", http.HandlerFunc(views.FirstComicView)) router.Get("/last", http.HandlerFunc(views.LastComicView)) router.Get("/random", http.HandlerFunc(views.RandomComicView)) router.Get("/admin", http.HandlerFunc(BasicAuth(views.ListView, user, pass))) router.Post("/api/comics", http.HandlerFunc(BasicAuth(views.CreateAPIView, user, pass))) router.Get("/api/comics", http.HandlerFunc(BasicAuth(views.ListAPIView, user, pass))) router.Get("/api/comics/:id", http.HandlerFunc(BasicAuth(views.GetAPIView, user, pass))) router.Del("/api/comics/:id", http.HandlerFunc(BasicAuth(views.DeleteAPIView, user, pass))) router.Put("/api/comics/:id", http.HandlerFunc(BasicAuth(views.UpdateAPIView, user, pass))) router.Get("/archive", http.HandlerFunc(views.ArchiveView)) router.Get("/atom", http.HandlerFunc(views.AtomView)) router.Get("/:id", http.HandlerFunc(views.GetComicView)) http.Handle("/", router) log.Printf("listen %s\n", listen) err := http.ListenAndServe(listen, nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
func main() { header := "-------------------------------------------------------------------------------\n RRDA (RRDA REST DNS API) 1.01 (c) by Frederic Cambus 2012-2014\n-------------------------------------------------------------------------------" host := flag.String("host", "127.0.0.1", "Set the server host") port := flag.String("port", "8080", "Set the server port") flag.Usage = func() { fmt.Println(header) fmt.Println("\nUSAGE :") flag.PrintDefaults() } flag.Parse() fmt.Println(header) fmt.Println("\nListening on :", *host+":"+*port) m := pat.New() m.Get("/:server/x/:ip", http.HandlerFunc(ptr)) m.Get("/:server/:domain/:querytype", http.HandlerFunc(query)) if err := http.ListenAndServe(*host+":"+*port, m); err != nil { fmt.Println("\nERROR :", err) os.Exit(1) } }
func SetupTaskRouter(pool db.DBPool, prefix string, writeToFile bool, middleware RestMiddleware) *pat.PatternServeMux { router := pat.New() taskServices := SetupTasks(pool) router.Get(prefix+"addresses", middleware(taskServices.getAllAddresses)) router.Get(prefix+"addresses/:address/requests", middleware(taskServices.getRequestsForAddress)) router.Get(prefix+"addresses/:address/requests/:requestid/tasks", middleware(taskServices.getTaskKeysForRequests)) router.Get(prefix+"addresses/:address/requests/:requestid/taskgraph", middleware(taskServices.getTaskGraphForRequest)) router.Get(prefix+"task/:taskKey", middleware(taskServices.getTaskByKey)) router.Get(prefix+"tasks/:taskid", middleware(taskServices.getTaskKeysForTask)) if writeToFile { //router.HandleFunc(prefix, middleware(taskServices.addTaskToFile)).Methods("POST") router.Post(prefix, middleware(taskServices.addTaskToFile)) } else { router.Post(prefix, http.HandlerFunc(taskServices.addTask)) } router.Post(prefix, http.HandlerFunc(taskServices.addTask)) router.Get(prefix, middleware(taskServices.getAllTasks)) return router }
func (srv *Server) run(lis net.Listener) { defer srv.tomb.Done() defer srv.wg.Wait() // wait for any outstanding requests to complete. srv.wg.Add(1) go func() { <-srv.tomb.Dying() lis.Close() srv.wg.Done() }() srv.wg.Add(1) go func() { err := srv.mongoPinger() srv.tomb.Kill(err) srv.wg.Done() }() // for pat based handlers, they are matched in-order of being // registered, first match wins. So more specific ones have to be // registered first. mux := pat.New() // For backwards compatibility we register all the old paths handleAll(mux, "/environment/:envuuid/log", &debugLogHandler{ httpHandler: httpHandler{state: srv.state}, logDir: srv.logDir}, ) handleAll(mux, "/environment/:envuuid/charms", &charmsHandler{ httpHandler: httpHandler{state: srv.state}, dataDir: srv.dataDir}, ) // TODO: We can switch from handleAll to mux.Post/Get/etc for entries // where we only want to support specific request methods. However, our // tests currently assert that errors come back as application/json and // pat only does "text/plain" responses. handleAll(mux, "/environment/:envuuid/tools", &toolsHandler{httpHandler{state: srv.state}}, ) handleAll(mux, "/environment/:envuuid/api", http.HandlerFunc(srv.apiHandler)) // For backwards compatibility we register all the old paths handleAll(mux, "/log", &debugLogHandler{ httpHandler: httpHandler{state: srv.state}, logDir: srv.logDir}, ) handleAll(mux, "/charms", &charmsHandler{ httpHandler: httpHandler{state: srv.state}, dataDir: srv.dataDir}, ) handleAll(mux, "/tools", &toolsHandler{httpHandler{state: srv.state}}, ) handleAll(mux, "/backup", &backupHandler{httpHandler{state: srv.state}}, ) handleAll(mux, "/", http.HandlerFunc(srv.apiHandler)) // The error from http.Serve is not interesting. http.Serve(lis, mux) }
func init() { m := pat.New() m.Get("/hello/:name", http.HandlerFunc(HelloServer)) // Register this pat with the default serve mux so that other packages // may also be exported. (i.e. /debug/pprof/*) http.Handle("/", m) }