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

Golang handlers.CompressHandler函数代码示例

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

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



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


示例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)))
}
开发者ID:dmcsorley,项目名称:avast,代码行数:26,代码来源:webserver.go


示例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())))
}
开发者ID:jerome-laforge,项目名称:mytweeter,代码行数:33,代码来源:webwserver.go


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


示例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")
	}
}
开发者ID:philipz,项目名称:scope,代码行数:57,代码来源:publisher_test.go


示例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
}
开发者ID:trwalker,项目名称:marvel-go,代码行数:9,代码来源:middleware_config.go


示例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
}
开发者ID:eklementev,项目名称:esp,代码行数:55,代码来源:server.go


示例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)
}
开发者ID:CNDonny,项目名称:scope,代码行数:55,代码来源:app_client_internal_test.go


示例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
}
开发者ID:thcyron,项目名称:tracklog,代码行数:51,代码来源:server.go


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


示例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)
}
开发者ID:shingetsu-gou,项目名称:shingetsu-gou,代码行数:15,代码来源:mch_datd.go


示例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))
}
开发者ID:bentranter,项目名称:bro-stream,代码行数:16,代码来源:main.go


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


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


示例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))
}
开发者ID:CNDonny,项目名称:scope,代码行数:42,代码来源:app_client_internal_test.go


示例16: TestAppClientDetails

func TestAppClientDetails(t *testing.T) {
	var (
		id      = "foobarbaz"
		version = "imalittleteapot"
		want    = xfer.Details{ID: id, Version: version}
	)

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		encoder := codec.NewEncoder(w, &codec.JsonHandle{})
		if err := encoder.Encode(want); err != nil {
			t.Fatal(err)
		}
	})

	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)
	}
	defer p.Stop()

	have, err := p.Details()
	if err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(want, have) {
		t.Error(test.Diff(want, have))
		return
	}
}
开发者ID:dilgerma,项目名称:scope,代码行数:42,代码来源:app_client_internal_test.go


示例17: ServerAction

func ServerAction(c *cli.Context) {
	router := httprouter.New()
	router.POST("/convert", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
		file, _, err := r.FormFile("messages")
		defer file.Close()
		WebCheck(w, err)

		b, err := ioutil.ReadAll(file)
		WebCheck(w, err)
		fbData := FromHTML(string(b))

		w.Header().Set("Content-type", "application/json")
		w.Write([]byte(ToJSON(fbData, false)))
	})
	router.ServeFiles("/*filepath", http.Dir("public"))

	addr := GetAddr()

	fmt.Println("Listening on", addr)
	check(http.ListenAndServe(addr, handlers.CompressHandler(router)))
}
开发者ID:Cretezy,项目名称:fddp,代码行数:21,代码来源:server.go


示例18: main

func main() {
	// Init bufferpool, used for rendering templates
	bufpool = bpool.NewBufferPool(48)

	// Load config file
	if _, err := toml.DecodeFile("config.ini", &conf); err != nil {
		log.Fatal("Couldn't parse config file: ", err)
	}

	// Setup remote repository
	repo = newRepo(
		conf.QuadStore.Endpoint,
		time.Duration(conf.QuadStore.OpenTimeout)*time.Millisecond,
		time.Duration(conf.QuadStore.ReadTimeout)*time.Millisecond,
	)

	// Parse Query bank
	qBank = sparql.LoadBank(bytes.NewBufferString(queries))

	// Register metrics
	status = registerMetrics()

	// HTTP routing
	mux := http.NewServeMux()
	var handler mainHandler
	mux.HandleFunc("/robots.txt", serveFile("data/robots.txt"))
	mux.HandleFunc("/css/styles.css", serveFile("data/css/styles.css"))
	mux.HandleFunc("/favicon.ico", serveFile("data/favicon.ico"))
	mux.HandleFunc("/.status", statusHandler)
	mux.HandleFunc("/literals", literalsHandler)
	mux.Handle("/", Timed(CountedByStatusXX(handler, "status", metrics.DefaultRegistry),
		"responseTime",
		metrics.DefaultRegistry))

	fmt.Printf("Listening on port %d ...\n", conf.ServePort)
	err := http.ListenAndServe(fmt.Sprintf(":%d", conf.ServePort), handlers.CompressHandler(mux))
	if err != nil {
		log.Println(err)
	}
}
开发者ID:knakk,项目名称:fenster,代码行数:40,代码来源:fenster.go


示例19: Setup

//Setup setups handlers for thread.cgi
func Setup(s *cgi.LoggingServeMux) {
	rtr := mux.NewRouter()

	cgi.RegistToRouter(rtr, cfg.ThreadURL+"/", printThreadIndex)

	reg := cfg.ThreadURL + "/{datfile:thread_[0-9A-F]+}/{id:[0-9a-f]{32}}/s{stamp:\\d+}.{thumbnailSize:\\d+x\\d+}.{suffix:.*}"
	cgi.RegistToRouter(rtr, reg, printAttach)

	reg = cfg.ThreadURL + "/{datfile:thread_[0-9A-F]+}/{id:[0-9a-f]{32}}/{stamp:\\d+}.{suffix:.*}"
	cgi.RegistToRouter(rtr, reg, printAttach)

	reg = cfg.ThreadURL + "/{path:[^/]+}{end:/?$}"
	cgi.RegistToRouter(rtr, reg, printThread)

	reg = cfg.ThreadURL + "/{path:[^/]+}/{id:[0-9a-f]{8}}{end:$}"
	cgi.RegistToRouter(rtr, reg, printThread)

	reg = cfg.ThreadURL + "/{path:[^/]+}/p{page:[0-9]+}{end:$}"
	cgi.RegistToRouter(rtr, reg, printThread)

	s.Handle(cfg.ThreadURL+"/", handlers.CompressHandler(rtr))
}
开发者ID:shingetsu-gou,项目名称:shingetsu-gou,代码行数:23,代码来源:thread_cgi.go


示例20: main

func main() {
	var (
		clientID      = flag.String("client-id", "", "soundcloud client id")
		clientSecret  = flag.String("client-secret", "", "soundcloud client secret")
		port          = flag.String("port", "3000", "address to bind the server on")
		callbackToken = flag.String("callback-token", "testToken", "OAuth token used to protect against CSRF attacks")
		appURL        = flag.String("app-url", "http://localhost:3000", "url of the app")
		store         = sessions.NewCookieStore([]byte("secret key"))
	)
	flag.Parse()

	config := &oauth2.Config{
		ClientID:     *clientID,
		ClientSecret: *clientSecret,
		RedirectURL:  *appURL + "/oauth2callback",
		Scopes: []string{
			"non-expiring",
		},
		Endpoint: oauth2.Endpoint{
			AuthURL:  "https://soundcloud.com/connect",
			TokenURL: "https://api.soundcloud.com/oauth2/token",
		},
	}
	m := pat.New()

	m.Get("/public/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, r.URL.Path[1:])
	})

	m.Get("/stream", getStream(store))
	m.Get("/oauth2callback", handleOAuth2Callback(store, config, *callbackToken))
	m.Post("/authorize", handleAuthorize(config, *callbackToken))
	m.Get("/", index(*clientID))

	handler := handlers.CompressHandler(handlers.LoggingHandler(os.Stdout, m))
	log.Printf("Listening on %s\n", *port)
	log.Fatal(http.ListenAndServe(":"+*port, handler))
}
开发者ID:stuartnelson3,项目名称:importcloud,代码行数:38,代码来源:main.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang handlers.LoggingHandler函数代码示例发布时间:2022-05-23
下一篇:
Golang handlers.CombinedLoggingHandler函数代码示例发布时间: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