本文整理汇总了Golang中github.com/gorilla/handlers.CompressHandler函数的典型用法代码示例。如果您正苦于以下问题:Golang CompressHandler函数的具体用法?Golang CompressHandler怎么用?Golang CompressHandler使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了CompressHandler函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
http.HandleFunc("/favicon.ico", iconHandler)
indexHandler := http.HandlerFunc(index)
aboutHandler := http.HandlerFunc(about)
logFile, err := os.OpenFile("server.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
http.Handle("/", handlers.LoggingHandler(logFile, handlers.CompressHandler(indexHandler)))
http.Handle("/about", handlers.LoggingHandler(logFile, handlers.CompressHandler(aboutHandler)))
server := &http.Server{
Addr: ":8080",
}
log.Println("Listening...")
server.ListenAndServe()
}
示例2: startWebserver
func startWebserver() {
processEnv()
router = mux.NewRouter()
router.HandleFunc("/ws", wrap(wsHandler))
dockerRouter := router.PathPrefix(fmt.Sprintf("/api/%v/docker", apiVersion)).Subrouter()
dockerRouter.HandleFunc("/containers", wrap(dockerClient.ContainersHandler))
dockerRouter.HandleFunc("/containers/graph", wrap(dockerClient.ContainerGraphHandler))
dockerRouter.HandleFunc("/container/{id}", wrap(dockerClient.ContainerHandler))
dockerRouter.HandleFunc("/images", wrap(dockerClient.ImagesHandler))
dockerRouter.HandleFunc("/image/history/{id}", wrap(dockerClient.HistoryHandler))
dockerRouter.HandleFunc("/info", wrap(dockerClient.InfoHandler))
consulRouter := router.PathPrefix(fmt.Sprintf("/api/%v/consul", apiVersion)).Subrouter()
consulRouter.HandleFunc("/datacenters", wrap(consulRegistry.DatacentersHandler))
consulRouter.HandleFunc("/nodes", wrap(consulRegistry.NodesHandler))
consulRouter.HandleFunc("/nodes/{dc}", wrap(consulRegistry.NodesHandler))
consulRouter.HandleFunc("/node/{name}", wrap(consulRegistry.NodeHandler))
consulRouter.HandleFunc("/health/{name}", wrap(consulRegistry.HealthHandler))
consulRouter.HandleFunc("/health/{name}/{dc}", wrap(consulRegistry.HealthHandler))
http.Handle("/", router)
loggedRouter := handlers.CombinedLoggingHandler(os.Stdout, router)
panic(http.ListenAndServe(addr, handlers.CompressHandler(loggedRouter)))
}
示例3: StartWebServer
func StartWebServer() error {
conf, err := config.GetConfig()
if err != nil {
return err
}
var hystrixTimeout time.Duration
conf.Hystrix.Timeout = strings.TrimSpace(conf.Hystrix.Timeout)
if conf.Hystrix.Timeout != "" {
hystrixTimeout, err = time.ParseDuration(conf.Hystrix.Timeout)
if err != nil || hystrixTimeout < time.Millisecond {
hystrixTimeout = time.Second
log15.Error("Use default time", "module", "hystrix", "timeout", hystrixTimeout)
}
}
hystrix.ConfigureCommand("waitFor", hystrix.CommandConfig{
Timeout: int(int64(hystrixTimeout) / int64(time.Millisecond)), // converted into Millisecond.
MaxConcurrentRequests: conf.Hystrix.MaxConcurrentRequests,
ErrorPercentThreshold: conf.Hystrix.ErrorPercentThreshold,
RequestVolumeThreshold: conf.Hystrix.RequestVolumeThreshold,
SleepWindow: conf.Hystrix.SleepWindow,
})
e := echo.New()
e.Post("/api/v1/tweet", createTweetV1)
e.Get("/api/v1/tweets/:id", getAllTweetForV1)
e.Get("/api/v1/wait/:timeout", waitFor)
e.Get("/api/v1/wait_protected/:timeout", waitForProtected)
e.Static("/", "www/static/")
logsrv := log15.New("pid", os.Getpid(), "addr", conf.Web.Address)
return listenAndServer(logsrv, conf.Web.Address, handlers.LoggingHandler(os.Stdout, handlers.CompressHandler(e.Router())))
}
示例4: registerWebRouter
// registerWebRouter - registers web router for serving minio browser.
func registerWebRouter(mux *router.Router, web *webAPIHandlers) {
// Initialize a new json2 codec.
codec := json2.NewCodec()
// Minio browser router.
webBrowserRouter := mux.NewRoute().PathPrefix(reservedBucket).Subrouter()
// Initialize json rpc handlers.
webRPC := jsonrpc.NewServer()
webRPC.RegisterCodec(codec, "application/json")
webRPC.RegisterCodec(codec, "application/json; charset=UTF-8")
webRPC.RegisterService(web, "Web")
// RPC handler at URI - /minio/webrpc
webBrowserRouter.Methods("POST").Path("/webrpc").Handler(webRPC)
webBrowserRouter.Methods("PUT").Path("/upload/{bucket}/{object:.+}").HandlerFunc(web.Upload)
webBrowserRouter.Methods("GET").Path("/download/{bucket}/{object:.+}").Queries("token", "{token:.*}").HandlerFunc(web.Download)
// Add compression for assets.
compressedAssets := handlers.CompressHandler(http.StripPrefix(reservedBucket, http.FileServer(assetFS())))
// Serve javascript files and favicon from assets.
webBrowserRouter.Path(fmt.Sprintf("/{assets:[^/]+.js|%s}", specialAssets)).Handler(compressedAssets)
// Serve index.html for rest of the requests.
webBrowserRouter.Path("/{index:.*}").Handler(indexHandler{http.StripPrefix(reservedBucket, http.FileServer(assetFS()))})
}
示例5: TestHTTPPublisher
func TestHTTPPublisher(t *testing.T) {
var (
token = "abcdefg"
id = "1234567"
rpt = report.MakeReport()
done = make(chan struct{})
)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if want, have := xfer.AuthorizationHeader(token), r.Header.Get("Authorization"); want != have {
t.Errorf("want %q, have %q", want, have)
}
if want, have := id, r.Header.Get(xfer.ScopeProbeIDHeader); want != have {
t.Errorf("want %q, have %q", want, have)
}
var have report.Report
reader := r.Body
var err error
if strings.Contains(r.Header.Get("Content-Encoding"), "gzip") {
reader, err = gzip.NewReader(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer reader.Close()
}
if err := gob.NewDecoder(reader).Decode(&have); err != nil {
t.Error(err)
return
}
if want := rpt; !reflect.DeepEqual(want, have) {
t.Error(test.Diff(want, have))
return
}
w.WriteHeader(http.StatusOK)
close(done)
})
s := httptest.NewServer(handlers.CompressHandler(handler))
defer s.Close()
p, err := xfer.NewHTTPPublisher(s.URL, token, id)
if err != nil {
t.Fatal(err)
}
if err := p.Publish(rpt); err != nil {
t.Error(err)
}
select {
case <-done:
case <-time.After(time.Millisecond):
t.Error("timeout")
}
}
示例6: RegisterMiddleware
func RegisterMiddleware(apiRouter *mux.Router) http.Handler {
var apiHandler http.Handler = apiRouter
apiHandler = handlers.CompressHandler(apiHandler)
apiHandler = handlers.CORS()(apiHandler)
apiHandler = ResponseHeaders(apiHandler)
return apiHandler
}
示例7: NewServer
// NewServer construct rest server listening specific host and port and routes requests by passed routes
func NewServer(props properties.Properties, routes PathHandlers) error {
bind := props.Get("rest.address") + ":" + props.Get("rest.port")
log.Println("start rest server on", bind)
listener, err := net.Listen("tcp", bind)
if err != nil {
return err
}
s := &server{
listener: listener,
m: &sync.Mutex{},
alive: true,
wg: &sync.WaitGroup{},
}
kit.SafeGo(func() error {
router := mux.NewRouter()
for path := range routes {
mh := handlers.MethodHandler{}
for method := range routes[path] {
log.Printf("setup rest handler %v %v\n", method, path)
mh[method] = s.wrapHandler(routes[path][method])
}
router.Path(path).Handler(mh)
}
handler := http.Handler(router)
compression, err := strconv.ParseBool(props.Get("rest.compression"))
if err == nil && compression {
log.Println("enable compression for rest server")
handler = handlers.CompressHandler(handler)
} else {
log.Println("no compression for rest server")
}
log.Println("rest server serves")
err = http.Serve(listener, handler)
if err != nil {
return err
}
return nil
})
kit.SafeGo(func() error {
<-registry.DoneChannel()
s.Stop()
return nil
})
return nil
}
示例8: TestStop
// Make sure Stopping a client works even if the connection or the remote app
// gets stuck for whatever reason.
// See https://github.com/weaveworks/scope/issues/1576
func TestStop(t *testing.T) {
var (
rpt = report.MakeReport()
stopHanging = make(chan struct{})
receivedReport = make(chan struct{})
)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
close(receivedReport)
<-stopHanging
})
s := httptest.NewServer(handlers.CompressHandler(handler))
defer s.Close()
u, err := url.Parse(s.URL)
if err != nil {
t.Fatal(err)
}
pc := ProbeConfig{
Token: "",
ProbeID: "",
Insecure: false,
}
p, err := NewAppClient(pc, u.Host, s.URL, nil)
if err != nil {
t.Fatal(err)
}
rp := NewReportPublisher(p)
// Make sure the app received our report and is stuck
for done := false; !done; {
select {
case <-receivedReport:
done = true
default:
if err := rp.Publish(rpt); err != nil {
t.Error(err)
}
time.Sleep(10 * time.Millisecond)
}
}
// Close the client while the app is stuck
p.Stop()
// Let the server go so that the test can end
close(stopHanging)
}
示例9: New
func New(conf *config.Config, db db.DB) (*Server, error) {
s := &Server{
config: conf,
db: db,
}
if !s.config.Server.Development {
tmpl, err := s.loadTemplates()
if err != nil {
return nil, err
}
s.tmpl = tmpl
}
n := negroni.Classic()
csrfHandler := csrf.Protect(
[]byte(s.config.Server.CSRFAuthKey),
csrf.Secure(!s.config.Server.Development),
csrf.FieldName("_csrf"),
)
n.UseFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
csrfHandler(next).ServeHTTP(w, r)
})
n.UseFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
handlers.HTTPMethodOverrideHandler(next).ServeHTTP(w, r)
})
n.UseFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
handlers.CompressHandler(next).ServeHTTP(w, r)
})
n.UseFunc(s.userAuthMiddleware)
r := httprouter.New()
r.ServeFiles("/static/*filepath", http.Dir(path.Join(DataDir, "public")))
r.GET("/signin", s.wrapHandler(s.HandleGetSignIn))
r.POST("/signin", s.wrapHandler(s.HandlePostSignIn))
r.POST("/signout", s.wrapHandler(s.HandlePostSignOut))
r.GET("/logs", s.wrapHandler(s.HandleGetLogs))
r.POST("/logs", s.wrapHandler(s.HandlePostLog))
r.GET("/logs/:id/download", s.wrapHandler(s.HandleDownloadLog))
r.GET("/logs/:id", s.wrapHandler(s.HandleGetLog))
r.PATCH("/logs/:id", s.wrapHandler(s.HandlePatchLog))
r.DELETE("/logs/:id", s.wrapHandler(s.HandleDeleteLog))
r.GET("/", s.wrapHandler(s.HandleDashboard))
n.UseHandler(r)
s.handler = n
return s, nil
}
示例10: main
func main() {
log.Infof("Starting Helphone API service on port %s", port)
router := service.NewRouter()
h := service.MuxWrapper{
IsReady: false,
Router: router,
}
go manager.Init()
handler := handlers.CompressHandler(handlers.ProxyHeaders(cors.Default().Handler(h.Router)))
log.Fatal(http.ListenAndServe(":"+port, handler))
}
示例11: Setup
//Setup setups handlers for 2ch interface.
func Setup(s *cgi.LoggingServeMux) {
log.Println("start 2ch interface")
rtr := mux.NewRouter()
cgi.RegistToRouter(rtr, "/2ch/", boardApp)
cgi.RegistToRouter(rtr, "/2ch/dat/{datkey:[^\\.]+}.dat", threadApp)
cgi.RegistToRouter(rtr, "/2ch/{board:[^/]+}/subject.txt", subjectApp)
cgi.RegistToRouter(rtr, "/2ch/subject.txt", subjectApp)
cgi.RegistToRouter(rtr, "/2ch/{board:[^/]+}/head.txt", headApp)
cgi.RegistToRouter(rtr, "/2ch/head.txt", headApp)
s.Handle("/2ch/", handlers.CompressHandler(rtr))
s.RegistCompressHandler("/test/bbs.cgi", postCommentApp)
}
示例12: main
func main() {
r := httprouter.New()
// Routes
r.GET("/", HomeHandler)
r.POST("/", UserRedirectHandler)
r.GET("/stream/:username", StreamHandler)
// Static assets
r.ServeFiles("/static/*filepath", http.Dir("static"))
fmt.Println("Serving HTTP on port 3000")
http.ListenAndServe(":3000", handlers.CompressHandler(r))
}
示例13: main
func main() {
log.SetOutput(os.Stderr)
port := flag.String("port", "8080", "server listening tcp port")
dbServer := flag.String("server", "localhost", "database server")
dbName := flag.String("db", "estia", "database name")
siteType := flag.String("type", "dir", "site path type zip or dir")
sitePath := flag.String("path", "wwwroot", "path containing site")
flag.Parse()
server = *dbServer
database = *dbName
db, err := mgo.Dial(server)
if err != nil {
log.Panic(err)
}
defer db.Close()
router := NewRouter()
if *siteType == "zip" {
rd, err := zip.OpenReader(*sitePath)
if err != nil {
log.Fatal(err)
}
fs := zipfs.New(rd, *sitePath)
router.PathPrefix("/").Handler(http.FileServer(httpfs.New(fs)))
} else {
router.PathPrefix("/").Handler(http.FileServer(http.Dir(*sitePath)))
}
withLog := handlers.LoggingHandler(os.Stdout, router)
withdb := WithDB(db, withLog)
withcors := handlers.CORS()(withdb)
withGz := handlers.CompressHandler(withcors)
log.Printf(
"%s\t%s",
"Server listening on ",
*port,
)
log.Fatal(http.ListenAndServeTLS(":"+*port, "cert.pem", "key.pem", context.ClearHandler(withGz)))
}
示例14: main
func main() {
configRead()
r := mux.NewRouter()
r.HandleFunc("/{template}", Handler)
fmt.Printf("accepting connections on %s:%s\n", Addr, Port)
err := http.ListenAndServe(
fmt.Sprintf("%s:%s", Addr, Port),
handlers.LoggingHandler(
os.Stdout,
handlers.CompressHandler(r)))
if err != nil {
log.Fatal(err)
}
}
示例15: dummyServer
func dummyServer(t *testing.T, expectedToken, expectedID string, expectedVersion string, expectedReport report.Report, done chan struct{}) *httptest.Server {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if have := r.Header.Get("Authorization"); fmt.Sprintf("Scope-Probe token=%s", expectedToken) != have {
t.Errorf("want %q, have %q", expectedToken, have)
}
if have := r.Header.Get(xfer.ScopeProbeIDHeader); expectedID != have {
t.Errorf("want %q, have %q", expectedID, have)
}
if have := r.Header.Get(xfer.ScopeProbeVersionHeader); expectedVersion != have {
t.Errorf("want %q, have %q", expectedID, have)
}
var have report.Report
reader := r.Body
var err error
if strings.Contains(r.Header.Get("Content-Encoding"), "gzip") {
reader, err = gzip.NewReader(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer reader.Close()
}
decoder := codec.NewDecoder(reader, &codec.MsgpackHandle{})
if err := decoder.Decode(&have); err != nil {
t.Error(err)
return
}
if !reflect.DeepEqual(expectedReport, have) {
t.Error(test.Diff(expectedReport, have))
return
}
w.WriteHeader(http.StatusOK)
done <- struct{}{}
})
return httptest.NewServer(handlers.CompressHandler(handler))
}