本文整理汇总了Golang中net/http.RedirectHandler函数的典型用法代码示例。如果您正苦于以下问题:Golang RedirectHandler函数的具体用法?Golang RedirectHandler怎么用?Golang RedirectHandler使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了RedirectHandler函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: InitStaticRouter
func InitStaticRouter(staticDir, staticETag string,
mgr *cbgt.Manager) *mux.Router {
prefix := ""
if mgr != nil {
prefix = mgr.Options()["urlPrefix"]
}
hfsStaticX := http.FileServer(assetFS())
router := mux.NewRouter()
router.StrictSlash(true)
router.Handle(prefix+"/",
http.RedirectHandler(prefix+"/index.html", 302))
router.Handle(prefix+"/index.html",
http.RedirectHandler(prefix+"/staticx/index.html", 302))
router.Handle(prefix+"/static/partials/index/start.html",
http.RedirectHandler(prefix+"/staticx/partials/index/start.html", 302))
router = rest.InitStaticRouterEx(router,
staticDir, staticETag, []string{
prefix + "/indexes",
prefix + "/nodes",
prefix + "/monitor",
prefix + "/manage",
prefix + "/logs",
prefix + "/debug",
}, http.RedirectHandler(prefix+"/staticx/index.html", 302), mgr)
router.PathPrefix(prefix + "/staticx/").Handler(
http.StripPrefix(prefix+"/staticx/", hfsStaticX))
return router
}
示例2: main
func main() {
mux := http.NewServeMux()
fileServer := http.FileServer(http.Dir("assets"))
mux.Handle("/nav/http-csp.html", cspNoReferrer(fileServer))
mux.Handle("/img/http-csp.html", cspNoReferrer(fileServer))
mux.Handle("/redirect/http-refresh", httpRefresher("../echo.txt"))
mux.Handle("/redirect/301.png", http.RedirectHandler("/echo.png", 301))
mux.Handle("/redirect/301.txt", http.RedirectHandler("/echo.txt", 301))
mux.Handle("/echo.txt", cacheControl(http.HandlerFunc(echoText)))
mux.Handle("/echo.png", cacheControl(http.HandlerFunc(echoImage)))
mux.Handle("/", fileServer)
go http.ListenAndServeTLS(":1443", "tls.crt", "tls.key", mux)
fmt.Println("Listening at https://localhost:1443")
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
<-sig
fmt.Println("")
}
示例3: urlMap
func urlMap(e *Env) {
// http.HandleFunc("/auth/logout", authLogout())
// redirect
//http.Handle("/some/path/robots.txt", http.RedirectHandler("/robots.txt", http.StatusMovedPermanently))
if FacebookLoginURL() != "" {
http.Handle("/login/facebook", Handler{e, HandleFacebookLogin})
http.Handle("/callback/facebook", LoginHandler{e, HandleFacebookCallback})
}
if GooglePlusLoginURL() != "" {
http.Handle("/login/google", Handler{e, HandleGooglePlusLogin})
http.Handle("/callback/google", LoginHandler{e, HandleGooglePlusCallback})
}
http.Handle("/logout", Handler{e, HandleLogout})
http.Handle("/robots.txt", http.RedirectHandler("/static/robots.txt", http.StatusMovedPermanently))
http.Handle("/favicon.ico", http.RedirectHandler("/static/favicon.ico", http.StatusMovedPermanently))
// Pages
http.Handle("/albums/", Handler{e, albumsHandler})
// Normal resources
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("public"))))
// http.HandleFunc("/albums/", requestAlbum())
http.Handle("/", Handler{e, rootHandler})
}
示例4: main
func main() {
http.HandleFunc("/", renderTemplate("index.html"))
http.HandleFunc("/sprites", renderTemplate("sprites.html"))
http.HandleFunc("/soundtrack/disc/1", renderTemplate("disc1.html"))
http.HandleFunc("/soundtrack/disc/2", renderTemplate("disc2.html"))
http.HandleFunc("/downloads/hawkthorne-win-x64.zip", trackDownload("hawkthorne-win-x64.zip"))
http.HandleFunc("/downloads/hawkthorne-win-x86.zip", trackDownload("hawkthorne-win-x86.zip"))
http.HandleFunc("/downloads/hawkthorne-osx.zip", trackDownload("hawkthrone-osx.zip"))
http.HandleFunc("/downloads/hawkthorne.love", trackDownload("hawkthorne.love"))
http.Handle("/sprites.html", http.RedirectHandler("/sprites", 301))
http.Handle("/audio.html", http.RedirectHandler("/soundtrack/disc/1", 301))
http.Handle("/soundtrack.html", http.RedirectHandler("/soundtrack/disc/1", 301))
http.Handle("/soundtrack-disc2.html", http.RedirectHandler("/soundtrack/disc/2", 301))
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
pfx := "/static/"
h := http.StripPrefix(pfx, http.FileServer(http.Dir("static")))
http.Handle(pfx, h)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
示例5: InitStaticRouter
func InitStaticRouter(staticDir, staticETag string) *mux.Router {
hfsStaticX := http.FileServer(assetFS())
router := mux.NewRouter()
router.StrictSlash(true)
router.Handle("/",
http.RedirectHandler("/staticx/index.html", 302))
router.Handle("/index.html",
http.RedirectHandler("/staticx/index.html", 302))
router.Handle("/static/partials/index/list.html",
http.RedirectHandler("/staticx/partials/index/list.html", 302))
router = rest.InitStaticRouter(router,
staticDir, staticETag, []string{
"/indexes",
"/nodes",
"/monitor",
"/manage",
"/logs",
"/debug",
}, http.RedirectHandler("/staticx/index.html", 302))
router.PathPrefix("/staticx/").Handler(
http.StripPrefix("/staticx/", hfsStaticX))
return router
}
示例6: createHandler
// Creates a GorillaMux router containing the HTTP handlers for a server.
func createHandler(sc *serverContext) http.Handler {
r := mux.NewRouter()
r.StrictSlash(true)
// Global operations:
r.Handle("/", makeHandler(sc, (*handler).handleRoot)).Methods("GET", "HEAD")
r.Handle("/_all_dbs", makeHandler(sc, (*handler).handleAllDbs)).Methods("GET", "HEAD")
if len(sc.databases) == 1 {
// If there is exactly one database we can handle the standard /_session by just redirecting
// it to that database's _session handler.
for _, db := range sc.databases {
path := "/" + db.dbcontext.Name
r.Handle("/_session", http.RedirectHandler(path+"/_session", http.StatusTemporaryRedirect))
r.Handle("/_persona", http.RedirectHandler(path+"/_persona", http.StatusTemporaryRedirect))
}
} else {
r.Handle("/_session", http.NotFoundHandler())
r.Handle("/_persona", http.NotFoundHandler())
}
// Operations on databases:
r.Handle("/{newdb}/", makeHandler(sc, (*handler).handleCreateDB)).Methods("PUT")
r.Handle("/{db}/", makeHandler(sc, (*handler).handleGetDB)).Methods("GET", "HEAD")
r.Handle("/{db}/", makeHandler(sc, (*handler).handleDeleteDB)).Methods("DELETE")
r.Handle("/{db}/", makeHandler(sc, (*handler).handlePostDoc)).Methods("POST")
// Special database URLs:
dbr := r.PathPrefix("/{db}/").Subrouter()
dbr.Handle("/_all_docs", makeHandler(sc, (*handler).handleAllDocs)).Methods("GET", "HEAD", "POST")
dbr.Handle("/_bulk_docs", makeHandler(sc, (*handler).handleBulkDocs)).Methods("POST")
dbr.Handle("/_bulk_get", makeHandler(sc, (*handler).handleBulkGet)).Methods("GET", "HEAD")
dbr.Handle("/_changes", makeHandler(sc, (*handler).handleChanges)).Methods("GET", "HEAD")
dbr.Handle("/_design/sync_gateway", makeHandler(sc, (*handler).handleDesign)).Methods("GET", "HEAD")
dbr.Handle("/_ensure_full_commit", makeHandler(sc, (*handler).handleEFC)).Methods("POST")
dbr.Handle("/_revs_diff", makeHandler(sc, (*handler).handleRevsDiff)).Methods("POST")
// Session/login URLs are per-database (unlike in CouchDB)
dbr.Handle("/_session", makeAdminHandler(sc, (*handler).handleSessionGET)).Methods("GET", "HEAD")
dbr.Handle("/_session", makeAdminHandler(sc, (*handler).handleSessionPOST)).Methods("POST")
if sc.config.Persona != nil {
dbr.Handle("/_persona", makeAdminHandler(sc, (*handler).handlePersonaPOST)).Methods("POST")
}
// Document URLs:
dbr.Handle("/_local/{docid}", makeHandler(sc, (*handler).handleGetLocalDoc)).Methods("GET", "HEAD")
dbr.Handle("/_local/{docid}", makeHandler(sc, (*handler).handlePutLocalDoc)).Methods("PUT")
dbr.Handle("/_local/{docid}", makeHandler(sc, (*handler).handleDelLocalDoc)).Methods("DELETE")
dbr.Handle("/{docid}", makeHandler(sc, (*handler).handleGetDoc)).Methods("GET", "HEAD")
dbr.Handle("/{docid}", makeHandler(sc, (*handler).handlePutDoc)).Methods("PUT")
dbr.Handle("/{docid}", makeHandler(sc, (*handler).handleDeleteDoc)).Methods("DELETE")
dbr.Handle("/{docid}/{attach}", makeHandler(sc, (*handler).handleGetAttachment)).Methods("GET", "HEAD")
// Fallbacks that have to be added last:
r.PathPrefix("/").Methods("OPTIONS").Handler(makeHandler(sc, (*handler).handleOptions))
r.PathPrefix("/").Handler(makeHandler(sc, (*handler).handleBadRoute))
return r
}
示例7: init
func init() {
http.HandleFunc("/assets/", assetsHandler)
http.HandleFunc("/page/", pageHandler)
http.HandleFunc("/_jt/cron/updateCounts", updateCountsHandler)
http.HandleFunc("/", notFoundHandler)
http.Handle("/resume.pdf", http.RedirectHandler(cdnUrl+"/assets/pdf/resume.pdf", http.StatusTemporaryRedirect))
http.Handle("/resume.tex", http.RedirectHandler(cdnUrl+"/assets/pdf/resume.tex", http.StatusTemporaryRedirect))
}
示例8: main
func main() {
// Add routes to the global handler
goji.Get("/", Root)
// Fully backwards compatible with net/http's Handlers
goji.Get("/greets", http.RedirectHandler("/", 301))
// Use your favorite HTTP verbs
goji.Post("/greets", NewGreet)
// Use Sinatra-style patterns in your URLs
goji.Get("/users/:name", GetUser)
// Goji also supports regular expressions with named capture groups.
goji.Get(regexp.MustCompile(`^/greets/(?P<id>\d+)$`), GetGreet)
// Middleware can be used to inject behavior into your app. The
// middleware for this application are defined in middleware.go, but you
// can put them wherever you like.
goji.Use(PlainText)
// If the patterns ends with "/*", the path is treated as a prefix, and
// can be used to implement sub-routes.
admin := web.New()
goji.Handle("/admin/*", admin)
// The standard SubRouter middleware helps make writing sub-routers
// easy. Ordinarily, Goji does not manipulate the request's URL.Path,
// meaning you'd have to repeat "/admin/" in each of the following
// routes. This middleware allows you to cut down on the repetition by
// eliminating the shared, already-matched prefix.
admin.Use(middleware.SubRouter)
// You can also easily attach extra middleware to sub-routers that are
// not present on the parent router. This one, for instance, presents a
// password prompt to users of the admin endpoints.
admin.Use(SuperSecure)
admin.Get("/", AdminRoot)
admin.Get("/finances", AdminFinances)
// Goji's routing, like Sinatra's, is exact: no effort is made to
// normalize trailing slashes.
goji.Get("/admin", http.RedirectHandler("/admin/", 301))
// Use a custom 404 handler
goji.NotFound(NotFound)
// Sometimes requests take a long time.
goji.Get("/waitforit", WaitForIt)
// Call Serve() at the bottom of your main() function, and it'll take
// care of everything else for you, including binding to a socket (with
// automatic support for systemd and Einhorn) and supporting graceful
// shutdown on SIGINT. Serve() is appropriate for both development and
// production.
goji.Serve()
}
示例9: main
func main() {
goji.Get("/", http.RedirectHandler("/list/1", http.StatusMovedPermanently))
goji.Get("/assets/bestxkcd.css", cssHandler)
goji.Get("/list", http.RedirectHandler("/list/1", http.StatusMovedPermanently))
goji.Get("/list/", http.RedirectHandler("/list/1", http.StatusMovedPermanently))
goji.Get("/list/:page", listHandler)
goji.Get("/vote", newVoteHandler)
goji.Get("/vote/", http.RedirectHandler("/vote", http.StatusMovedPermanently))
goji.Get("/vote/:token", voteHandler)
goji.Serve()
}
示例10: init
func init() {
api := Router.PathPrefix("/api").Subrouter()
api.Path("/jobs").Methods("GET").Handler(http.RedirectHandler("jobs/", http.StatusMovedPermanently))
api.Path("/jobs/").Methods("GET").HandlerFunc(jobsIndexHandler)
api.Path("/jobs/").Methods("POST").HandlerFunc(jobCreateHandler)
api.Path("/jobs/{job}").Methods("GET").HandlerFunc(jobGetHandler)
api.Path("/jobs/{job}/builds").Methods("GET").Handler(http.RedirectHandler("builds/", http.StatusMovedPermanently))
api.Path("/jobs/{job}/builds/").Methods("GET").HandlerFunc(buildsIndexHandler)
api.Path("/jobs/{job}/builds/").Methods("POST").HandlerFunc(buildCreateHandler)
// api.Path("/jobs/{job}/builds/{build}").Methods("GET").HandlerFunc(buildGetHandler)
}
示例11: main
func main() {
// gtk.Init(&os.Args)
// builder := gtk.Builder()
// builder.AddFromFile(locateUiFile())
// builder.ConnectSignals(nil)
// ui.Init(builder)
http.RedirectHandler(url, code)
http.Handler("/", http.RedirectHandler("/edit", 301))
http.HandleFunc("/edit", handleEdit)
http.HandleFunc("/send", handleSend)
http.ListenAndServe(":8080", nil)
}
示例12: InitStaticRouterEx
// InitStaticRouterEx is like InitStaticRouter, but with optional
// manager parameter for more options.
func InitStaticRouterEx(r *mux.Router, staticDir, staticETag string,
pages []string, pagesHandler http.Handler,
mgr *cbgt.Manager) *mux.Router {
prefix := ""
if mgr != nil {
prefix = mgr.Options()["urlPrefix"]
}
PIndexTypesInitRouter(r, "static.before", mgr)
var s http.FileSystem
if staticDir != "" {
if _, err := os.Stat(staticDir); err == nil {
log.Printf("http: serving assets from staticDir: %s", staticDir)
s = http.Dir(staticDir)
}
}
if s == nil {
log.Printf("http: serving assets from embedded data")
s = AssetFS()
}
r.PathPrefix(prefix + "/static/").Handler(
http.StripPrefix(prefix+"/static/",
ETagFileHandler{http.FileServer(s), staticETag}))
// Bootstrap UI insists on loading templates from this path.
r.PathPrefix(prefix + "/template/").Handler(
http.StripPrefix(prefix+"/template/",
ETagFileHandler{http.FileServer(s), staticETag}))
// If client ask for any of the pages, redirect.
for _, p := range pages {
if pagesHandler != nil {
r.PathPrefix(p).Handler(pagesHandler)
} else {
r.PathPrefix(p).Handler(RewriteURL("/", http.FileServer(s)))
}
}
r.Handle(prefix+"/index.html",
http.RedirectHandler(prefix+"/static/index.html", 302))
r.Handle(prefix+"/",
http.RedirectHandler(prefix+"/static/index.html", 302))
PIndexTypesInitRouter(r, "static.after", mgr)
return r
}
示例13: main
func main() {
// Handle debugging
if debug || os.Getenv("DEBUG") == "true" {
debug = true // Just in case
debugOut = log.New(os.Stdout, "[DEBUG]", log.Lshortfile)
}
debugOut.Printf("Pre-Config:\n%+v\n", GlobalConfig.Map())
// Load Configs
if configFolder != "" {
loadConfigs(configFolder)
} else if cf := os.Getenv("CONFIGFOLDER"); cf != "" {
loadConfigs(cf)
}
debugOut.Printf("Post-Config\n%+v\n", GlobalConfig.Map())
// Setup AWS stuff
initAWS()
// Goji!!!
if GlobalConfig.IsNotNull("serverHeader") {
headerString := GlobalConfig.Get("serverHeader")
if headerString != "yes" {
FULLVERSION = headerString
}
goji.Use(ServerHeader)
}
goji.Get("/", http.RedirectHandler(GlobalConfig.Get("formURL"), 301))
goji.Get("/health", healthHandler)
goji.Post("/upload", uploadHandler)
goji.Get("/upload", http.RedirectHandler(GlobalConfig.Get("getRedirect"), 301))
// Allow handling of static content for webform, thank you page, etc.
if GlobalConfig.IsNotNull("staticPath") && GlobalConfig.IsNotNull("staticURL") {
debugOut.Printf("Static handling of '%s' mapped to '%s'\n", GlobalConfig.Get("staticURL"), GlobalConfig.Get("staticPath"))
goji.Handle(GlobalConfig.Get("staticURL"),
http.StripPrefix(strings.TrimRight(GlobalConfig.Get("staticURL"), "*"),
http.FileServer(http.Dir(GlobalConfig.Get("staticPath")))))
}
goji.Handle("/*", defaultHandler)
goji.Serve()
}
示例14: RegisterHandlers
func RegisterHandlers(mux httpMux.Mux, containerManager manager.Manager, httpAuthFile, httpAuthRealm, httpDigestFile, httpDigestRealm, prometheusEndpoint string) error {
// Basic health handler.
if err := healthz.RegisterHandler(mux); err != nil {
return fmt.Errorf("failed to register healthz handler: %s", err)
}
// Validation/Debug handler.
mux.HandleFunc(validate.ValidatePage, func(w http.ResponseWriter, r *http.Request) {
err := validate.HandleRequest(w, containerManager)
if err != nil {
fmt.Fprintf(w, "%s", err)
}
})
// Register API handler.
if err := api.RegisterHandlers(mux, containerManager); err != nil {
return fmt.Errorf("failed to register API handlers: %s", err)
}
// Redirect / to containers page.
mux.Handle("/", http.RedirectHandler(pages.ContainersPage, http.StatusTemporaryRedirect))
var authenticated bool = false
// Setup the authenticator object
if httpAuthFile != "" {
glog.Infof("Using auth file %s", httpAuthFile)
secrets := auth.HtpasswdFileProvider(httpAuthFile)
authenticator := auth.NewBasicAuthenticator(httpAuthRealm, secrets)
mux.HandleFunc(static.StaticResource, authenticator.Wrap(staticHandler))
if err := pages.RegisterHandlersBasic(mux, containerManager, authenticator); err != nil {
return fmt.Errorf("failed to register pages auth handlers: %s", err)
}
authenticated = true
}
if httpAuthFile == "" && httpDigestFile != "" {
glog.Infof("Using digest file %s", httpDigestFile)
secrets := auth.HtdigestFileProvider(httpDigestFile)
authenticator := auth.NewDigestAuthenticator(httpDigestRealm, secrets)
mux.HandleFunc(static.StaticResource, authenticator.Wrap(staticHandler))
if err := pages.RegisterHandlersDigest(mux, containerManager, authenticator); err != nil {
return fmt.Errorf("failed to register pages digest handlers: %s", err)
}
authenticated = true
}
// Change handler based on authenticator initalization
if !authenticated {
mux.HandleFunc(static.StaticResource, staticHandlerNoAuth)
if err := pages.RegisterHandlersBasic(mux, containerManager, nil); err != nil {
return fmt.Errorf("failed to register pages handlers: %s", err)
}
}
collector := metrics.NewPrometheusCollector(containerManager)
prometheus.MustRegister(collector)
http.Handle(prometheusEndpoint, prometheus.Handler())
return nil
}
示例15: 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)
}