本文整理汇总了Golang中github.com/bmizerany/pat.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: New
// 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
}
示例2: main
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)
}
示例3: setupHandlers
// 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)
})
}
示例4: Run
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
}
示例5: HTTPServe
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: ")
}
}
示例6: newServer
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
}
示例7: main
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)
}
}
示例8: New
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
}
示例9: StartEndpoint
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
}
示例10: main
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)
}
}
示例11: init
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)
}
示例12: main
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)
}
}
示例13: NewServer
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
}
示例14: registerRoutes
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)
}
示例15: RegisterRoutes
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
}