本文整理匯總了Golang中github.com/gorilla/pat.New函數的典型用法代碼示例。如果您正苦於以下問題:Golang New函數的具體用法?Golang New怎麽用?Golang New使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了New函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Run
func Run(address string) {
// routes
r := pat.New()
r.Get("/ws", wsHandler)
r.Get("/js/", staticHandler)
r.Get("/css/", staticHandler)
r.Get("/images/", staticHandler)
r.Get("/templates/", staticHandler)
r.Get("/fonts/", staticHandler)
r.Get("/api/authors/page~{page:[0-9]+}/limit~{limit:[0-9]+}/search={search:[а-яА-Яa-zA-Z0-9]*}", authorsFindHandler)
r.Get("/api/authors/id~{id:[0-9]+}", authorGetByIdHandler)
r.Get("/api/station/id~{id:[0-9]+}", stationHandler)
r.Get("/api/books/id~{id:[0-9]+}", getBookHandler)
r.Get("/api/books/page~{page:[0-9]+}/limit~{limit:[0-9]+}/author~{author}/search={search:[а-яА-Яa-zA-Z0-9]*}", booksHandler)
r.Get("/api/file/list/book~{book:[0-9]+}", getBookFileListHandler)
r.Post("/api/history/book~{book:[0-9]+}", addHistoryHandler)
r.Get("/api/history/page~{page:[0-9]+}/limit~{limit:[0-9]+}", getHistoryHandler)
r.Get("/", homeHandler)
http.Handle("/", r)
if err := http.ListenAndServe(address, nil); err != nil {
fmt.Println(err.Error())
}
}
示例2: main
func main() {
flag.Parse()
var err error
log.Print("Dialing mongodb database")
mongodb_session, err = mgo.Dial(MONGODB_URL)
if err != nil {
panic(err)
}
log.Print("Succesfully dialed mongodb database")
err = mongodb_session.DB(MONGODB_DATABASE).Login(MONGODB_USERNAME, MONGODB_PASSWORD)
r := pat.New()
//Create a unique index on 'guid', so that entires will not be duplicated
//Any duplicate entries will be dropped silently when insertion is attempted
guid_index := mgo.Index{
Key: []string{"guid"},
Unique: true,
DropDups: true,
Background: true,
Sparse: true,
}
mongodb_session.DB(MONGODB_DATABASE).C(BLOGPOSTS_DB).EnsureIndex(guid_index)
if *fetchposts {
feeds, err := parseFeeds(FEEDS_LIST_FILENAME)
if err != nil {
panic(err)
}
for _, feed_info := range feeds {
if len(feed_info) != 2 {
panic(fmt.Errorf("Expect csv with 2 elements per row; received row with %d elements", len(feed_info)))
}
feed_url := feed_info[0]
feed_author := feed_info[1]
log.Printf("Found %s", feed_url)
go func(uri string, author string) {
scrapeRss(uri, author)
}(feed_url, feed_author)
}
} else {
log.Print("Skipping fetching posts - blog posts will NOT be updated")
}
//Order of routes matters
//Routes *will* match prefixes
http.Handle("/static/", http.FileServer(http.Dir("public")))
r.Get("/feeds/all", serveFeeds)
r.Get("/authors/all", serveAuthorInfo)
r.Get("/", servePosts)
//r.Get("/", serveHome)
http.Handle("/", r)
log.Printf("Starting HTTP server listening on %v", *httpAddr)
if err := http.ListenAndServe(*httpAddr, nil); err != nil {
log.Fatalf("Error listening, %v", err)
}
}
示例3: main
func main() {
// Load config file
cfg, err := config.Load()
if err != nil {
fmt.Println(err)
return
}
// Instantiate logger
logger, err := log.New(cfg.LogFile)
if err != nil {
fmt.Println(err)
return
}
pool := image.NewImagePool(cfg.ImageDir)
handlers := handler.New(pool, logger)
router := pat.New()
router.Get("/images/{uuid}/file", handlers.GetImageFile())
router.Get("/images/{uuid}", handlers.GetImage())
router.Get("/images", handlers.ListImages())
router.Delete("/images/{uuid}", handlers.DeleteImage())
router.Post("/images/{uuid}", handlers.ImageAction())
router.Post("/images", handlers.CreateImage())
router.Put("/images/{uuid}/file", handlers.AddImageFile())
router.Get("/ping", handlers.Ping())
http.Handle("/", router)
fmt.Printf("Listening for http connections on %s\n", cfg.Listen)
if err := http.ListenAndServe(cfg.Listen, nil); err != nil {
fmt.Println(err)
}
}
示例4: main
func main() {
err := SignatureCreateKey()
if err != nil {
log.Fatal("SignatureCreateKey: Is the Redis database running?: ", err)
return
}
m := pat.New()
m.Get("/static/{path}", http.HandlerFunc(StaticServer))
m.Post("/setup", http.HandlerFunc(SetupHandler))
m.Post("/user/key/{type}", http.HandlerFunc(SecretKeySetupHandler))
// Control flow is: /authgh -> github -> /oauth2callbackgh
m.Get("/authgh", http.HandlerFunc(AuthHandlerGH))
m.Get("/oauth2callbackgh", http.HandlerFunc(Oauth2callbackHandlerGH))
// Control flow is: /auth -> google -> /oauth2callback
m.Get("/auth", http.HandlerFunc(authHandler))
m.Get("/oauth2callback", http.HandlerFunc(oauth2callbackHandler))
m.Get("/signout", http.HandlerFunc(signoutHandler))
m.Post("/signout", http.HandlerFunc(signoutHandler))
m.Post("/signature", http.HandlerFunc(SignatureVerifyHandler))
http.Handle("/ws/glass/", websocket.Handler(WSGlassHandler))
http.Handle("/ws/client", websocket.Handler(WSWebHandler))
http.Handle("/ws/client/", websocket.Handler(WSWebHandler))
http.Handle("/ws/web", websocket.Handler(WSWebHandler))
http.Handle("/ws/web/", websocket.Handler(WSWebHandler))
m.Get("/", http.HandlerFunc(PlaygroundServer))
http.Handle("/", m)
err = http.ListenAndServe(":"+servePort, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
示例5: TestExecEarlyExit
func TestExecEarlyExit(test *testing.T) {
config.ServerURI = "127.0.0.1:1236"
mux := pat.New()
normalPing(mux)
normalExec(test, mux)
listen := startServer(test, mux)
defer listen.Close()
errChan := make(chan error)
go func() {
// need to use a pipe so that no EOF is returned. this was causing test to fail very quickly
r, _ := io.Pipe()
out := &bytes.Buffer{}
err := execInternal("exec", "cmd=exit", r, out)
test.Log("exited", err)
if err != nil {
errChan <- err
return
}
close(errChan)
}()
select {
case <-time.After(time.Second * 4):
test.Log("timed out...")
test.FailNow()
case err := <-errChan:
if err == nil {
return
}
test.Log(err)
test.FailNow()
}
}
示例6: registerRoutes
// registerRoutes
func registerRoutes() (*pat.Router, error) {
lumber.Debug("[PULSE :: API] Registering routes...")
//
router := pat.New()
//
router.Get("/ping", func(rw http.ResponseWriter, req *http.Request) {
rw.Write([]byte("pong"))
})
router.Options("/", cors)
router.Get("/keys", keysRequest)
router.Get("/tags", tagsRequest)
router.Get("/latest/{stat}", doCors(latestStat))
router.Get("/hourly/{stat}", doCors(hourlyStat))
router.Get("/daily/{stat}", doCors(dailyStat))
router.Get("/daily_peaks/{stat}", doCors(dailyStat))
// only expose alert routes if alerting configured
if viper.GetString("kapacitor-address") != "" {
// todo: maybe get and list tasks from kapacitor
router.Post("/alerts", doCors(setAlert))
router.Put("/alerts", doCors(setAlert))
router.Delete("/alerts/{id}", doCors(deleteAlert))
}
return router, nil
}
示例7: routes
func routes() *pat.Router {
router := pat.New()
// balancing
router.Delete("/services/{svcId}/servers/{srvId}", deleteServer)
router.Get("/services/{svcId}/servers/{srvId}", getServer)
router.Put("/services/{svcId}/servers", putServers)
router.Post("/services/{svcId}/servers", postServer)
router.Get("/services/{svcId}/servers", getServers)
router.Delete("/services/{svcId}", deleteService)
router.Put("/services/{svcId}", putService)
router.Get("/services/{svcId}", getService)
router.Post("/services", postService)
router.Put("/services", putServices)
router.Get("/services", getServices)
// routing
router.Delete("/routes", deleteRoute)
router.Put("/routes", putRoutes)
router.Get("/routes", getRoutes)
router.Post("/routes", postRoute)
// certificates
router.Delete("/certs", deleteCert)
router.Put("/certs", putCerts)
router.Get("/certs", getCerts)
router.Post("/certs", postCert)
// ips
router.Delete("/vips", deleteVip)
router.Put("/vips", putVips)
router.Get("/vips", getVips)
router.Post("/vips", postVip)
return router
}
示例8: main
func main() {
list := NewList()
gcmPusher := NewGCMPusher(*gcmKey)
wsPusher := NewWSPusher()
bus := NewEventBus([]Subscriber{gcmPusher, wsPusher})
r := pat.New()
corsHandler := CORSHandler()
r.Get("/list", IndexHandler(list))
r.Add("OPTIONS", "/list", corsHandler)
r.Put("/list/{urn}", SetHandler(list, bus))
r.Add("OPTIONS", "/list/{urn}", corsHandler)
r.Post("/list/{urn}/{action:(play|pause)}", PlaybackHandler(list, bus))
r.Add("OPTIONS", "/list/{urn}/{action:(play|pause)}", corsHandler)
r.Delete("/list/{urn}", DeleteHandler(list, bus))
r.Add("OPTIONS", "/list/{urn}", corsHandler)
r.Handle("/subscribe/gcm", GCMSubscriptionHandler(gcmPusher))
r.Handle("/subscribe/ws", WSSubscriptionHandler(wsPusher))
err := http.ListenAndServe(*listen, r)
if err != nil {
log.Fatal(err)
}
}
示例9: launchServer
func launchServer(flag *flag.Flag) error {
path, err := config.GetString("assets")
if err != nil {
return errors.New("No assets folder specified in config file.")
}
scheduler.Run()
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir(path))))
r := pat.New()
r.Post("/schedules/{scheduleId}", updateSchedule)
r.Get("/schedules/{scheduleId}/edit", editSchedule)
r.Get("/schedules/new", newSchedule)
r.Post("/schedules", createSchedule)
r.Get("/valves/{valveId}/edit", editValve)
r.Get("/valves/{valveId}/open", openValve)
r.Get("/valves/{valveId}/close", closeValve)
r.Post("/valves/{valveId}", updateValve)
r.Get("/valves/{valveId}", showValve)
r.Get("/manual", manual)
r.Get("/", homepage)
http.Handle("/", r)
initializeTemplates(path)
err = http.ListenAndServe(":7777", nil)
return err
}
示例10: registerRoutes
// registerRoutes registers all api routes with the router
func registerRoutes() (*pat.Router, error) {
config.Log.Debug("[sherpa/api] Registering routes...\n")
//
router := pat.New()
//
router.Get("/ping", func(rw http.ResponseWriter, req *http.Request) {
rw.Write([]byte("pong"))
})
// templates
router.Delete("/templates/{id}", handleRequest(deleteTemplate))
router.Get("/templates/{id}", handleRequest(getTemplate))
router.Post("/templates", handleRequest(postTemplate))
router.Get("/templates", handleRequest(getTemplates))
// builds
router.Delete("/builds/{id}", handleRequest(deleteBuild))
router.Get("/builds/{id}", handleRequest(getBuild))
router.Post("/builds", handleRequest(postBuild))
router.Get("/builds", handleRequest(getBuilds))
return router, nil
}
示例11: App
func App() http.Handler {
p := pat.New()
p.Get("/get", func(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(201)
fmt.Fprintln(res, "METHOD:"+req.Method)
fmt.Fprint(res, "Hello from Get!")
})
p.Delete("/delete", func(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(201)
fmt.Fprintln(res, "METHOD:"+req.Method)
fmt.Fprint(res, "Goodbye")
})
p.Post("/post", func(res http.ResponseWriter, req *http.Request) {
fmt.Fprintln(res, "METHOD:"+req.Method)
fmt.Fprint(res, "NAME:"+req.PostFormValue("name"))
})
p.Put("/put", func(res http.ResponseWriter, req *http.Request) {
fmt.Fprintln(res, "METHOD:"+req.Method)
fmt.Fprint(res, "NAME:"+req.PostFormValue("name"))
})
p.Post("/sessions/set", func(res http.ResponseWriter, req *http.Request) {
sess, _ := Store.Get(req, "my-session")
sess.Values["name"] = req.PostFormValue("name")
sess.Save(req, res)
})
p.Get("/sessions/get", func(res http.ResponseWriter, req *http.Request) {
sess, _ := Store.Get(req, "my-session")
if sess.Values["name"] != nil {
fmt.Fprint(res, "NAME:"+sess.Values["name"].(string))
}
})
return p
}
示例12: GetRouter
func GetRouter() *pat.Router {
r := pat.New()
r.Get("/mail/healthcheck", HelloWorldHandler)
r.Post("/mail/contactus", ContactUsHandler)
return r
}
示例13: Listen
// Listen binds to httpBindAddr
func Listen(httpBindAddr string, Asset func(string) ([]byte, error), exitCh chan int, registerCallback func(http.Handler)) {
log.Info("[HTTP] Binding to address: %s", httpBindAddr)
pat := pat.New()
registerCallback(pat)
f := func(w http.ResponseWriter, req *http.Request) {
if Authorised == nil {
pat.ServeHTTP(w, req)
return
}
u, pw, ok := req.BasicAuth()
if !ok || !Authorised(u, pw) {
w.Header().Set("WWW-Authenticate", "Basic")
w.WriteHeader(401)
return
}
pat.ServeHTTP(w, req)
}
err := http.ListenAndServe(httpBindAddr, http.HandlerFunc(f))
if err != nil {
log.Fatalf("[HTTP] Error binding to address %s: %s", httpBindAddr, err)
}
}
示例14: main
func main() {
SignatureCreateKey()
m := pat.New()
m.Get("/static/{path}", http.HandlerFunc(StaticServer))
m.Post("/notify/{key}", http.HandlerFunc(NotifyServer))
m.Post("/notify/", http.HandlerFunc(NotifyServer))
m.Post("/setup", http.HandlerFunc(SetupHandler))
m.Post("/user/key/{type}", http.HandlerFunc(SecretKeySetupHandler))
// Control flow is: /auth -> google -> /oauth2callback
m.Get("/auth", http.HandlerFunc(authHandler))
m.Get("/oauth2callback", http.HandlerFunc(oauth2callbackHandler))
m.Post("/signout", http.HandlerFunc(signoutHandler))
m.Post("/flags", http.HandlerFunc(FlagsHandler))
m.Get("/flags", http.HandlerFunc(FlagsHandler))
m.Delete("/flags", http.HandlerFunc(FlagsHandler))
m.Post("/signature", http.HandlerFunc(SignatureVerifyHandler))
http.Handle("/ws/glass/", websocket.Handler(WSGlassHandler))
http.Handle("/ws/web", websocket.Handler(WSWebHandler))
http.Handle("/ws/web/", websocket.Handler(WSWebHandler))
m.Get("/", http.HandlerFunc(PlaygroundServer))
http.Handle("/", m)
err := http.ListenAndServe(":"+servePort, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
示例15: main
func main() {
// Initialize any provider
provider := google.New()
// Bare http
http.Handle("/auth/google/authorize", id.Authorize(provider))
http.Handle("/auth/google/callback", id.Callback(provider, "auth/restricted"))
http.Handle("/auth/restricted", id.Middleware(id.Verify, id.Verified))
// Default mux
serveMux := http.NewServeMux()
serveMux.Handle("/auth/google/authorize", id.Authorize(provider))
serveMux.Handle("/auth/google/callback", id.Callback(provider, "auth/restricted"))
serveMux.Handle("/auth/restricted", id.Middleware(id.Verify, id.Verified))
// Gorilla's Pat. Requires type assertion.
p := pat.New()
p.Get("/auth/google/authorize", id.Authorize(provider).(http.HandlerFunc))
p.Get("/auth/google/callback", id.Callback(provider, "auth/restricted").(http.HandlerFunc))
// Gorilla's Mux
m := mux.NewRouter()
m.Handle("/auth/google/authorize", id.Authorize(provider))
m.Handle("/auth/google/callback", id.Callback(provider, "auth/restricted"))
// Julien Schmidt's httprouter
r := httprouter.New()
r.GET("/httprouter/auth/google/authorize", id.HTTPRouterAuthorize(provider))
r.GET("/httprouter/auth/google/callback", id.HTTPRouterCallback(provider, "auth/restricted"))
log.Printf("Serving HTTP on port 3000")
log.Fatal(http.ListenAndServe(":3000", serveMux))
}