• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang mux.NewRouter函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/gorilla/mux.NewRouter函数的典型用法代码示例。如果您正苦于以下问题:Golang NewRouter函数的具体用法?Golang NewRouter怎么用?Golang NewRouter使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了NewRouter函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
}
开发者ID:mvpmvh,项目名称:interpose,代码行数:28,代码来源:main.go


示例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)
}
开发者ID:martianov,项目名称:go-imb,代码行数:27,代码来源:go_imb.go


示例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
}
开发者ID:gotstago,项目名称:go-tarabish,代码行数:28,代码来源:routes.go


示例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
}
开发者ID:arvinkulagin,项目名称:beeper,代码行数:35,代码来源:main.go


示例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
}
开发者ID:jlgerber,项目名称:sg-restful,代码行数:31,代码来源:main.go


示例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!")
	}
}
开发者ID:mssola,项目名称:todo,代码行数:60,代码来源:topics_test.go


示例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
}
开发者ID:liyu4,项目名称:home,代码行数:40,代码来源:muxer.go


示例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))
}
开发者ID:cncodog,项目名称:shpd,代码行数:33,代码来源:api.go


示例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
}
开发者ID:Kalpanat,项目名称:CMPE-273-Lab3,代码行数:29,代码来源:server.go


示例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
}
开发者ID:shihuacai1989,项目名称:pushgo,代码行数:58,代码来源:app.go


示例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),
	))
}
开发者ID:mikeflynn,项目名称:go-alexa,代码行数:56,代码来源:skillserver.go


示例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()}
	}
}
开发者ID:ycaihua,项目名称:gizmo,代码行数:13,代码来源:router.go


示例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())
}
开发者ID:nivertech,项目名称:kala,代码行数:10,代码来源:api_test.go


示例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")),
	)

}
开发者ID:travjones,项目名称:cm_app,代码行数:53,代码来源:main.go


示例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)
}
开发者ID:bbh-labs,项目名称:openinnovation-old,代码行数:51,代码来源:main.go


示例16: main

func main() {
	var err error
	db, err = sqlx.Connect("postgres", "user=postgres password=postgres dbname=messenger sslmode=disable")
	if err != nil {
		log.Fatalln(err)
	}
	CreateSchema(false)

	r := mux.NewRouter()
	authBase := mux.NewRouter()
	apiBase := mux.NewRouter()
	auth := authBase.PathPrefix("/auth").Subrouter()
	api := apiBase.PathPrefix("/api").Subrouter()

	r.PathPrefix("/auth").Handler(negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
		negroni.Wrap(authBase),
	))

	jwtSecret = "a very secret string"
	// must be authenticated to  use api routes
	jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
		ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
			return []byte(jwtSecret), nil
		},
		SigningMethod: jwt.SigningMethodHS256,
		UserProperty:  "jwt_user",
	})
	r.PathPrefix("/api").Handler(negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
		negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
		negroni.Wrap(apiBase),
	))

	// used to check if server is live
	auth.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "pong")
	}).Methods("POST")

	auth.Path("/signup").HandlerFunc(Signup).Methods("POST")
	auth.Path("/login").HandlerFunc(Login).Methods("POST")

	api.Path("/messages").HandlerFunc(NewMessage).Methods("POST")
	api.HandleFunc("/{user}/messages", GetUsersMessages).Methods("GET")

	log.Fatal(http.ListenAndServe(":8080", r))

}
开发者ID:kevhouck,项目名称:go-messenger-server,代码行数:50,代码来源:server.go


示例17: main

func main() {
	middle := interpose.New()

	// First call middleware that may manipulate HTTP headers, since
	// they must be called before the HTTP body is manipulated

	// Using Gorilla framework's combined logger
	middle.Use(middleware.GorillaLog())

	//Using Negroni's Gzip functionality
	middle.Use(middleware.NegroniGzip(gzip.DefaultCompression))

	// Now call middleware that can manipulate the HTTP body

	// Define the router. Note that we can add the router to our
	// middleware stack before we define the routes, if we want.
	router := mux.NewRouter()
	middle.UseHandler(router)

	// Configure our router
	router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"])
	})

	// Define middleware that will apply to only some routes
	greenMiddle := interpose.New()

	// Tell the main router to send /green requests to our subrouter.
	// Again, we can do this before defining the full middleware stack.
	router.Methods("GET").PathPrefix("/green").Handler(greenMiddle)

	// Within the secondary middleware, just like above, we want to call anything that
	// will modify the HTTP headers before anything that will modify the body
	greenMiddle.UseHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		rw.Header().Set("X-Favorite-Color", "green")
	}))

	// Finally, define a sub-router based on our love of the color green
	// When you call any url such as http://localhost:3001/green/man , you will
	// also see an HTTP header sent called X-Favorite-Color with value "green"
	greenRouter := mux.NewRouter().Methods("GET").PathPrefix("/green").Subrouter() //Headers("Accept", "application/json")
	greenMiddle.UseHandler(greenRouter)

	greenRouter.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page, green %s!", mux.Vars(req)["user"])
	})

	http.ListenAndServe(":3001", middle)
}
开发者ID:mvpmvh,项目名称:interpose,代码行数:49,代码来源:example1.go


示例18: main

func main() {
	flag.Parse()

	markers = make(map[string]map[string]string)
	portString := strconv.Itoa(port)

	stop := make(chan bool)
	go func() {
		for {
			select {
			case <-time.After(1 * time.Second):
				update()
			case <-stop:
				return
			}
		}
	}()

	r := mux.NewRouter()
	r.HandleFunc("/gps", gps)
	http.Handle("/", &CorsServer{r})
	fmt.Printf("bus-server listening on port %s\n", portString)
	err := http.ListenAndServe(":"+portString, nil)
	if err != nil {
		panic(err)
	}
}
开发者ID:krisrang,项目名称:bus-server,代码行数:27,代码来源:main.go


示例19: Main

func Main() {
	config = LoadConfig()
	BaseUrl = config.BaseUrl
	ArticlePrefix = config.ArticlePrefix

	log.LogTo(config.LogTo, config.LogLevel)
	logger = log.NewPrefixLogger("MAIN")

	db = newDb()
	defer db.Close()

	artclesPath := fmt.Sprintf("/%s", ArticlePrefix)
	articlePath := fmt.Sprintf("/%s/{source_slug}/{article_slug}/{article_id:[0-9]+}", ArticlePrefix)

	r := mux.NewRouter()
	r.HandleFunc(articlePath, serve(articleHandler)).Methods("GET")
	r.HandleFunc(articlePath, serve(reFetchArticleHandler)).Methods("PUT")
	r.HandleFunc(artclesPath, serve(articlesHandler)).Methods("GET")
	r.NotFoundHandler = http.HandlerFunc(unknownHandler)

	port := "8080" //os.Getenv("PORT")

	logger.Info("Listening on port %s\n", port)
	http.ListenAndServe(":"+port, r)
}
开发者ID:rastasheep,项目名称:utisak-worker,代码行数:25,代码来源:api.go


示例20: CreateRouter

func CreateRouter(server contracts.Server) (*mux.Router, error) {
	r := mux.NewRouter()
	m := map[string]map[string]HttpApiFunc{
		"GET": {
			"/replays/{id:[0-9]+}": server.GetReplay,
		},
		"POST": {
			"/join":   server.JoinMatch,
			"/create": server.CreateMatch,
			"/start":  server.StartMatch,
		},
	}

	for method, routes := range m {
		for route, handler := range routes {
			localRoute := route
			localHandler := handler
			localMethod := method
			f := makeHttpHandler(localMethod, localRoute, localHandler)

			r.Path(localRoute).Methods(localMethod).HandlerFunc(f)
		}
	}

	return r, nil
}
开发者ID:ralreegorganon,项目名称:vaal,代码行数:26,代码来源:server.go



注:本文中的github.com/gorilla/mux.NewRouter函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang mux.Vars函数代码示例发布时间:2022-05-23
下一篇:
Golang mux.HandleFunc函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap