本文整理匯總了Golang中github.com/gorilla/mux.NewRouter函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewRouter函數的具體用法?Golang NewRouter怎麽用?Golang NewRouter使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewRouter函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: main
func main() {
middle := interpose.New()
router := mux.NewRouter()
router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, `<h1>Welcome to the public page!</h1><p><a href="/protected/">Rabbit hole</a></p>`)
})
middle.UseHandler(router)
// Now we will define a sub-router that uses the BasicAuth middleware
// When you call any url starting with the path /protected, you will need to authenticate
protectedRouter := mux.NewRouter().Methods("GET").PathPrefix("/protected").Subrouter()
protectedRouter.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "Welcome to the protected page!")
})
// Define middleware that pertains to the part of the site protected behind HTTP Auth
// and add the protected router to the protected middleware
protectedMiddlew := interpose.New()
protectedMiddlew.Use(middleware.BasicAuth("john", "doe"))
protectedMiddlew.UseHandler(protectedRouter)
// Add the protected middleware and its router to the main router
router.Methods("GET").PathPrefix("/protected").Handler(protectedMiddlew)
http.ListenAndServe(":3001", middle)
}
示例2: main
func main() {
configuration := readConfiguration()
dbSession := DBConnect(configuration.MongodbUrl)
DBEnsureIndicesAndDefaults(dbSession, configuration.MongodbDatabaseName)
// handle all requests by serving a file of the same name
fs := http.Dir(configuration.Webapp)
fileHandler := http.FileServer(fs)
// setup routes
router := mux.NewRouter()
router.Handle("/", http.RedirectHandler("/webapp/index.html", 302))
router.PathPrefix("/webapp").Handler(http.StripPrefix("/webapp", fileHandler))
authRouterBase := mux.NewRouter()
router.PathPrefix("/auth").Handler(negroni.New(DBMiddleware(dbSession, configuration.MongodbDatabaseName), negroni.Wrap(authRouterBase)))
authRouter := authRouterBase.PathPrefix("/auth").Subrouter()
authRouter.HandleFunc("/login", Login).Methods("POST")
apiRouterBase := mux.NewRouter()
router.PathPrefix("/api").Handler(negroni.New(DBMiddleware(dbSession, configuration.MongodbDatabaseName), JWTMiddleware(), negroni.Wrap(apiRouterBase)))
apiRouter := apiRouterBase.PathPrefix("/api").Subrouter()
apiRouter.HandleFunc("/me", Me).Methods("GET")
http.ListenAndServe(fmt.Sprintf(":%v", configuration.Port), router)
}
示例3: BuildRoutes
// BuildRoutes returns the routes for the application.
func BuildRoutes() http.Handler {
router := mux.NewRouter()
router.HandleFunc("/", HomeHandler)
router.HandleFunc("/login-success", LoginSuccessHandler)
router.HandleFunc("/verify", VerifyHandler)
router.HandleFunc("/logout", LogoutHandler)
router.HandleFunc("/game", GameHandler)
// profile routes with LoginRequiredMiddleware
profileRouter := mux.NewRouter()
profileRouter.HandleFunc("/profile", ProfileHandler)
router.PathPrefix("/profile").Handler(negroni.New(
negroni.HandlerFunc(LoginRequiredMiddleware),
negroni.Wrap(profileRouter),
))
// apply the base middleware to the main router
n := negroni.New(
negroni.HandlerFunc(CsrfMiddleware),
negroni.HandlerFunc(UserMiddleware),
)
n.UseHandler(router)
return n
}
示例4: main
func main() {
logger := log.NewLogger()
cfg := config.Default()
flag.StringVar(&cfg.WSAddress, "ws", cfg.WSAddress, "Websocket address")
flag.StringVar(&cfg.RESTAddress, "rest", cfg.RESTAddress, "REST address")
flag.StringVar(&cfg.Origin, "o", cfg.Origin, "Origin URL")
file := flag.String("config", "", "Config file")
flag.Parse()
if *file != "" {
err := config.FromFile(*file, &cfg)
if err != nil {
logger.Err.Fatal(err)
}
flag.Parse()
}
broker := pubsub.NewBroker()
go func() {
wsRouter := mux.NewRouter()
wsRouter.Handle("/{id}", handlers.WSHandler{Broker: broker, Config: cfg, Logger: logger})
logger.Out.Println("Listening websockets on", cfg.WSAddress)
logger.Err.Fatal(http.ListenAndServe(cfg.WSAddress, wsRouter))
}()
go func() {
restRouter := mux.NewRouter()
restRouter.Handle("/topic", handlers.List{Broker: broker, Logger: logger}).Methods("GET")
restRouter.Handle("/topic", handlers.Add{Broker: broker, Logger: logger}).Methods("POST")
restRouter.Handle("/topic/{id}", handlers.Pub{Broker: broker, Logger: logger}).Methods("POST")
restRouter.Handle("/topic/{id}", handlers.Del{Broker: broker, Logger: logger}).Methods("DELETE")
restRouter.Handle("/ping", handlers.Ping{Logger: logger}).Methods("GET")
logger.Out.Println("Listening REST on", cfg.RESTAddress)
logger.Err.Fatal(http.ListenAndServe(cfg.RESTAddress, restRouter))
}()
wait := make(chan struct{})
<-wait
}
示例5: router
func router(config clientConfig) *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/", indexHandler(config))
r.Handle("/favicon.ico", http.NotFoundHandler())
authMiddleware := negroni.HandlerFunc(ShotgunAuthMiddleware(config))
entityRoutes := mux.NewRouter()
entityRoutes.Path("/{entity_type}/{id:[0-9]+}").HandlerFunc(entityGetHandler(config)).Methods("GET")
entityRoutes.Path("/{entity_type}/{id:[0-9]+}").HandlerFunc(entityUpdateHandler(config)).Methods("PATCH")
entityRoutes.Path("/{entity_type}/{id:[0-9]+}").
HandlerFunc(entityDeleteHandler(config)).Methods("DELETE")
entityRoutes.Path("/{entity_type}/{id:[0-9]+}/revive").
HandlerFunc(entityReviveHandler(config)).Methods("POST")
// entityRoutes.Path("/{entity_type}/{id:[0-9]+}/followers").
// HandlerFunc(entityGetFollowersHandler(config)).Methods("GET")
//entityRoutes.Path("/{entity_type}/{id:[0-9]+}/followers").
// HandlerFunc(entityAddFollowersHandler(config)).Methods("POST")
//entityRoutes.Path("/{entity_type}/{id:[0-9]+}/followers/{user_type}/{user_id:[0-9]+}").
// HandlerFunc(entityDeleteFollowersHandler(config)).Methods("DELETE")
entityRoutes.Path("/{entity_type}").HandlerFunc(entityGetAllHandler(config)).Methods("GET")
entityRoutes.Path("/{entity_type}").HandlerFunc(entityCreateHandler(config)).Methods("POST")
// Adds auth on the sub router so that / can be accessed freely.
r.PathPrefix("/{entity_type}").Handler(negroni.New(
authMiddleware,
negroni.Wrap(entityRoutes),
))
return r
}
示例6: TestTopicsCreateJson
func TestTopicsCreateJson(t *testing.T) {
initTestDB()
defer closeTestDB()
// We try to create a topic for the first time.
body := "{\"name\":\"mssola\"}"
reader := strings.NewReader(body)
req, err := http.NewRequest("POST", "/topics", reader)
if err != nil {
t.Fatalf("Expected to be nil: %v", err)
}
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
m := mux.NewRouter()
m.HandleFunc("/topics", TopicsCreate)
m.ServeHTTP(w, req)
var topic Topic
decoder := json.NewDecoder(w.Body)
err = decoder.Decode(&topic)
if err != nil {
t.Fatalf("Expected to be nil: %v", err)
}
var t1 Topic
err = Db.SelectOne(&t1, "select * from topics")
if err != nil {
t.Fatalf("Expected to be nil: %v", err)
}
if t1.ID != topic.ID {
t.Fatalf("Got %v; Expected: %v", t1.ID, topic.ID)
}
if t1.Name != topic.Name {
t.Fatalf("Got %v; Expected: %v", t1.Name, topic.Name)
}
// Now let's try it with the same name.
reader2 := strings.NewReader(body)
req, err = http.NewRequest("POST", "/topics", reader2)
if err != nil {
t.Fatalf("Expected to be nil: %v", err)
}
req.Header.Set("Content-Type", "application/json")
w1 := httptest.NewRecorder()
m = mux.NewRouter()
m.HandleFunc("/topics", TopicsCreate)
m.ServeHTTP(w1, req)
var resp lib.Response
decoder = json.NewDecoder(w1.Body)
err = decoder.Decode(&resp)
if err != nil {
t.Fatalf("Expected to be nil: %v", err)
}
if resp.Error != "Failed!" {
t.Fatalf("Got %v; Expected: %v", resp.Error, "Failed!")
}
}
示例7: MakeMuxer
// MakeMuxer creates a http.Handler to manage all list operations. If
// a prefix is given, that prefix will be the first part of the
// url. This muxer will provide the following handlers and return a
// RESTful 404 on all others.
//
// GET prefix + / Get all lists.
// POST prefix + / Create a new list.
//
// GET prefix + /{key}/ Get the list for the given key.
// PUT prefix + /{key}/ Update the list with the given key.
// DELETE prefix + /{key}/ Delete the list with the given key.
//
// See the functions related to these urls for more details on what
// each one does and the requirements behind it.
func MakeMuxer(prefix string) http.Handler {
var m *mux.Router
// Pass through the prefix if we got one.
if prefix == "" {
m = mux.NewRouter()
} else {
m = mux.NewRouter().PathPrefix(prefix).Subrouter()
}
// Get all lists.
m.HandleFunc("/", GetAllLists).Methods("GET")
// Make a new list.
m.HandleFunc("/", PostList).Methods("POST")
// Singe list operations.
m.HandleFunc("/{key}/", GetList).Methods("GET")
m.HandleFunc("/{key}/", PutList).Methods("PUT")
m.HandleFunc("/{key}/", DeleteList).Methods("DELETE")
// Everything else fails.
m.HandleFunc("/{path:.*}", gorca.NotFoundFunc)
return m
}
示例8: Run
func (a *Api) Run() error {
globalMux := http.NewServeMux()
authRouter := mux.NewRouter()
authRouter.HandleFunc("/auth/login", a.login).Methods("GET")
authRouter.HandleFunc("/auth/logout", a.logout).Methods("GET")
authRouter.HandleFunc("/auth/callback", a.authCallback).Methods("GET")
apiRouter := mux.NewRouter()
apiRouter.Handle("/api/domains", a.authRequiredMiddleware(http.HandlerFunc(a.domains))).Methods("GET")
apiRouter.Handle("/api/domains", a.authRequiredMiddleware(http.HandlerFunc(a.addDomain))).Methods("POST")
apiRouter.Handle("/api/domains/{prefix:.*}", a.authRequiredMiddleware(http.HandlerFunc(a.removeDomain))).Methods("DELETE")
apiRouter.HandleFunc("/api/ip", a.getIP).Methods("GET")
//globalMux.Handle("/api/", apiRouter)
globalMux.Handle("/api/", apiRouter)
globalMux.Handle("/auth/", authRouter)
// global handler
globalMux.Handle("/", http.FileServer(http.Dir("static")))
s := &http.Server{
Addr: a.listenAddr,
Handler: context.ClearHandler(globalMux),
}
if err := s.ListenAndServe(); err != nil {
return err
}
return http.ListenAndServe(a.listenAddr, context.ClearHandler(globalMux))
}
示例9: main
func main() {
finish := make(chan bool)
router1 := mux.NewRouter()
router1.HandleFunc("/keys", handleGetAllKey1).Methods("GET")
router1.HandleFunc("/keys/{key}", handleGetKey1).Methods("GET")
router1.HandleFunc("/keys/{key}/{value}", handlePutKey1).Methods("PUT")
go func() {
http.ListenAndServe(":3000", router1)
}()
router2 := mux.NewRouter()
router2.HandleFunc("/keys", handleGetAllKey2).Methods("GET")
router2.HandleFunc("/keys/{key}", handleGetKey2).Methods("GET")
router2.HandleFunc("/keys/{key}/{value}", handlePutKey2).Methods("PUT")
go func() {
http.ListenAndServe(":3001", router2)
}()
router3 := mux.NewRouter()
router3.HandleFunc("/keys", handleGetAllKey3).Methods("GET")
router3.HandleFunc("/keys/{key}", handleGetKey3).Methods("GET")
router3.HandleFunc("/keys/{key}/{value}", handlePutKey3).Methods("PUT")
go func() {
http.ListenAndServe(":3002", router3)
}()
<-finish
}
示例10: Run
// Start the application
func (a *Application) Run() (errChan chan error) {
errChan = make(chan error)
clientMux := mux.NewRouter()
clientMux.HandleFunc("/status/", a.handlers.StatusHandler)
clientMux.HandleFunc("/realstatus/", a.handlers.RealStatusHandler)
clientMux.Handle("/", websocket.Server{Handler: a.handlers.PushSocketHandler,
Handshake: a.checkOrigin})
endpointMux := mux.NewRouter()
endpointMux.HandleFunc("/update/{key}", a.handlers.UpdateHandler)
endpointMux.HandleFunc("/status/", a.handlers.StatusHandler)
endpointMux.HandleFunc("/realstatus/", a.handlers.RealStatusHandler)
endpointMux.HandleFunc("/metrics/", a.handlers.MetricsHandler)
routeMux := mux.NewRouter()
routeMux.HandleFunc("/route/{uaid}", a.handlers.RouteHandler)
// Weigh the anchor!
go func() {
clientLn := a.server.ClientListener()
if a.log.ShouldLog(INFO) {
a.log.Info("app", "Starting WebSocket server",
LogFields{"addr": clientLn.Addr().String()})
}
clientSrv := &http.Server{
Handler: &LogHandler{clientMux, a.log},
ErrorLog: log.New(&LogWriter{a.log.Logger, "worker", ERROR}, "", 0)}
errChan <- clientSrv.Serve(clientLn)
}()
go func() {
endpointLn := a.server.EndpointListener()
if a.log.ShouldLog(INFO) {
a.log.Info("app", "Starting update server",
LogFields{"addr": endpointLn.Addr().String()})
}
endpointSrv := &http.Server{
Handler: &LogHandler{endpointMux, a.log},
ErrorLog: log.New(&LogWriter{a.log.Logger, "endpoint", ERROR}, "", 0)}
errChan <- endpointSrv.Serve(endpointLn)
}()
go func() {
routeLn := a.router.Listener()
if a.log.ShouldLog(INFO) {
a.log.Info("app", "Starting router",
LogFields{"addr": routeLn.Addr().String()})
}
routeSrv := &http.Server{
Handler: &LogHandler{routeMux, a.log},
ErrorLog: log.New(&LogWriter{a.log.Logger, "router", ERROR}, "", 0)}
errChan <- routeSrv.Serve(routeLn)
}()
return errChan
}
示例11: Init
func Init(apps map[string]interface{}, router *mux.Router) {
Applications = apps
// /echo/* Endpoints
echoRouter := mux.NewRouter()
// /* Endpoints
pageRouter := mux.NewRouter()
for uri, meta := range Applications {
switch app := meta.(type) {
case EchoApplication:
handlerFunc := func(w http.ResponseWriter, r *http.Request) {
echoReq := r.Context().Value("echoRequest").(*EchoRequest)
echoResp := NewEchoResponse()
if echoReq.GetRequestType() == "LaunchRequest" {
if app.OnLaunch != nil {
app.OnLaunch(echoReq, echoResp)
}
} else if echoReq.GetRequestType() == "IntentRequest" {
if app.OnIntent != nil {
app.OnIntent(echoReq, echoResp)
}
} else if echoReq.GetRequestType() == "SessionEndedRequest" {
if app.OnSessionEnded != nil {
app.OnSessionEnded(echoReq, echoResp)
}
} else {
http.Error(w, "Invalid request.", http.StatusBadRequest)
}
json, _ := echoResp.String()
w.Header().Set("Content-Type", "application/json;charset=UTF-8")
w.Write(json)
}
if app.Handler != nil {
handlerFunc = app.Handler
}
echoRouter.HandleFunc(uri, handlerFunc).Methods("POST")
case StdApplication:
pageRouter.HandleFunc(uri, app.Handler).Methods(app.Methods)
}
}
router.PathPrefix("/echo/").Handler(negroni.New(
negroni.HandlerFunc(validateRequest),
negroni.HandlerFunc(verifyJSON),
negroni.Wrap(echoRouter),
))
router.PathPrefix("/").Handler(negroni.New(
negroni.Wrap(pageRouter),
))
}
示例12: NewRouter
// NewRouter will return the router specified by the server
// config. If no Router value is supplied, the server
// will default to using Gorilla mux.
func NewRouter(cfg *Config) Router {
switch cfg.RouterType {
case "fast", "httprouter":
return &FastRouter{httprouter.New()}
case "gorilla":
return &GorillaRouter{mux.NewRouter()}
default:
return &GorillaRouter{mux.NewRouter()}
}
}
示例13: TestSetupApiRoutes
func (a *ApiTestSuite) TestSetupApiRoutes() {
db := &job.MockDB{}
cache := job.NewMockCache()
r := mux.NewRouter()
SetupApiRoutes(r, cache, db)
a.NotNil(r)
a.IsType(r, mux.NewRouter())
}
示例14: main
func main() {
ren := render.New(render.Options{
Layout: "shared/layout",
IsDevelopment: true,
})
//sessions
store := cookiestore.New([]byte("secret"))
//db
// db, err := sqlx.Connect("postgres", os.Getenv("CONNECTIONSTRING"))
db, err := sqlx.Connect("postgres", "user=travisjones dbname=cm_app sslmode=disable")
if err != nil {
log.Println("Error initializing database...")
log.Fatalln(err)
}
c := ctx{db, ren}
n := negroni.New()
nauth := negroni.New()
//routers
router := mux.NewRouter()
authRouter := mux.NewRouter()
//AUTHORIZED ROUTES
authRouter.HandleFunc("/", c.Home)
router.Handle("/", nauth).Methods("GET")
//OPEN ROUTES
router.HandleFunc("/account/login", c.Login).Methods("GET")
router.HandleFunc("/account/login", c.LoginPost).Methods("POST")
router.HandleFunc("/account/signup", c.Signup).Methods("GET")
router.HandleFunc("/account/signup", c.SignupPost).Methods("POST")
router.HandleFunc("/account/logout", c.Logout).Methods("GET")
//Middleware
nauth.Use(negroni.HandlerFunc(RequireAuth))
nauth.UseHandler(authRouter)
//Sessions
n.Use(sessions.Sessions("authex", store))
n.Use(negroni.NewStatic(http.Dir("public")))
n.UseHandler(router)
n.Run(
fmt.Sprint(":", os.Getenv("PORT")),
)
}
示例15: main
func main() {
flag.Parse()
store.Init()
p := func(name string, handler http.HandlerFunc) http.Handler {
return prometheus.InstrumentHandler(name, handler)
}
router := mux.NewRouter()
router.Handle("/metrics", prometheus.Handler())
router.Handle("/", p("/", home))
router.Handle("/login", p("/login", login))
router.Handle("/verify", p("/verify", verify))
apiRouter := mux.NewRouter()
apiRouter.Handle("/api/logout", p("/logout", logout))
apiRouter.Handle("/api/user", p("/user", user))
apiRouter.Handle("/api/user/project", p("/user/project", userProject))
apiRouter.Handle("/api/project", p("/project", project))
apiRouter.Handle("/api/project/member", p("/task/member", member))
apiRouter.Handle("/api/task", p("/task", task))
apiRouter.Handle("/api/task/worker", p("/task/worker", worker))
apiRouter.Handle("/api/milestone", p("/milestone", milestone))
apiRouter.Handle("/api/friend", p("/friend", friend))
apiRouter.Handle("/api/chat", p("/chat", chat))
apiRouter.HandleFunc("/api/ws", ws)
router.PathPrefix("/api").Handler(negroni.New(
negroni.HandlerFunc(apiMiddleware),
negroni.Wrap(apiRouter),
))
adminRouter := mux.NewRouter()
adminRouter.Handle("/api/admin/user", p("/admin/user", adminUser))
adminRouter.Handle("/api/admin/project", p("/admin/project", adminProject))
router.PathPrefix("/api/admin").Handler(negroni.New(
negroni.HandlerFunc(adminMiddleware),
negroni.Wrap(adminRouter),
))
go h.run()
n := negroni.Classic()
n.UseHandler(router)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
n.Run(":" + port)
}