当前位置: 首页>>代码示例>>Golang>>正文


Golang gzip.All函数代码示例

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


在下文中一共展示了All函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: standardHttp

// standardHttp starts serving standard HTTP (api/web) requests, to be used by normal clients
func standardHttp(discovery bool) {
	m := martini.Classic()

	switch strings.ToLower(config.Config.AuthenticationMethod) {
	case "basic":
		{
			if config.Config.HTTPAuthUser == "" {
				// Still allowed; may be disallowed in future versions
				log.Warning("AuthenticationMethod is configured as 'basic' but HTTPAuthUser undefined. Running without authentication.")
			}
			m.Use(auth.Basic(config.Config.HTTPAuthUser, config.Config.HTTPAuthPassword))
		}
	case "multi":
		{
			if config.Config.HTTPAuthUser == "" {
				// Still allowed; may be disallowed in future versions
				log.Fatal("AuthenticationMethod is configured as 'multi' but HTTPAuthUser undefined")
			}

			m.Use(auth.BasicFunc(func(username, password string) bool {
				if username == "readonly" {
					// Will be treated as "read-only"
					return true
				}
				return auth.SecureCompare(username, config.Config.HTTPAuthUser) && auth.SecureCompare(password, config.Config.HTTPAuthPassword)
			}))
		}
	default:
		{
			// We inject a dummy User object because we have function signatures with User argument in api.go
			m.Map(auth.User(""))
		}
	}

	m.Use(gzip.All())
	// Render html templates from templates directory
	m.Use(render.Renderer(render.Options{
		Directory:       "resources",
		Layout:          "templates/layout",
		HTMLContentType: "text/html",
	}))
	m.Use(martini.Static("resources/public"))

	inst.SetMaintenanceOwner(logic.ThisHostname)

	log.Info("Starting HTTP")

	if discovery {
		go logic.ContinuousDiscovery()
	}
	inst.ReadClusterAliases()

	http.API.RegisterRequests(m)
	http.Web.RegisterRequests(m)

	// Serve
	if err := nethttp.ListenAndServe(config.Config.ListenAddress, m); err != nil {
		log.Fatale(err)
	}
}
开发者ID:shuhaowu,项目名称:orchestrator,代码行数:61,代码来源:http.go

示例2: main

func main() {
	m := martini.Classic()

	m.Use(gzip.All())

	// render html templates from templates directory
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))

	m.Use(DB())

	m.Get("/", func(r render.Render, db *mgo.Database) {
		data := map[string]interface{}{"quotes": GetAll(db)}
		r.HTML(200, "list", data)
	})

	m.Post("/", binding.Form(Quote{}), func(r render.Render, db *mgo.Database, quote Quote) {
		db.C("quotes").Insert(quote)
		data := map[string]interface{}{"quotes": GetAll(db)}
		r.HTML(200, "list", data)
	})

	m.Run()
}
开发者ID:aeyoll,项目名称:go-quotes,代码行数:25,代码来源:server.go

示例3: main

func main() {
	log.Info("启动")
	//读取配置文件
	base.BaseConfig.Read("config.json")
	// 初始化数据库
	base.InitDb()
	// 检查文件完整性
	//err := base.CheckFiles()
	//if(err!=nil){
	//  log.Error(err)
	//  return
	//}
	m := martini.Classic()
	// gzip支持
	m.Use(gzip.All())
	// 模板支持
	m.Use(render.Renderer())
	//
	m.Get("/meta.js", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/javascript")
		w.Write([]byte(base.GetMetaJs()))
	})
	// websocket 支持
	m.Get("/ws", websocket.Handler(base.WsHandler).ServeHTTP)
	m.NotFound(func(r render.Render) {
		r.HTML(404, "404", nil)
	})
	log.Info(fmt.Sprintf("访问地址 http://localhost:%d", base.BaseConfig.Web.Port))
	// 端口号
	http.ListenAndServe(fmt.Sprintf(":%d", base.BaseConfig.Web.Port), m)
	// m.Run()
	log.Info("退出")
}
开发者ID:xuender,项目名称:pen,代码行数:33,代码来源:main.go

示例4: App

func App() *martini.ClassicMartini {
	m := martini.Classic()

	m.Use(gzip.All())

	m.Use(render.Renderer(render.Options{
		Directory: "templates",
	}))

	m.Use(cors.Allow(&cors.Options{
		AllowAllOrigins: true,
	}))

	m.Get("", Index)

	m.Group("/repos", func(r martini.Router) {
		r.Get("", ReposIndex)
		r.Get("/:name", ReposShow)
	})

	m.Group("/orgs", func(r martini.Router) {
		r.Get("", OrgsIndex)
		r.Get("/:id", OrgsShow)
	})

	m.Group("/users", func(r martini.Router) {
		r.Get("", UserIndex)
		r.Get("/:id", UserShow)
	})

	m.Get("/stats", StatsIndex)
	m.Get("/issues", IssuesIndex)

	return m
}
开发者ID:jakeporter,项目名称:govcode.org,代码行数:35,代码来源:main.go

示例5: Http

// Http starts serving HTTP (api/web) requests
func Http() {
	martini.Env = martini.Prod
	m := martini.Classic()
	if config.Config.HTTPAuthUser != "" {
		m.Use(auth.Basic(config.Config.HTTPAuthUser, config.Config.HTTPAuthPassword))
	}

	m.Use(gzip.All())
	// Render html templates from templates directory
	m.Use(render.Renderer(render.Options{
		Directory:       "resources",
		Layout:          "templates/layout",
		HTMLContentType: "text/html",
	}))
	m.Use(martini.Static("resources/public"))

	go agent.ContinuousOperation()

	log.Infof("Starting HTTP on port %d", config.Config.HTTPPort)

	http.API.RegisterRequests(m)

	// Serve
	if config.Config.UseSSL {
		log.Info("Serving via SSL")
		err := nethttp.ListenAndServeTLS(fmt.Sprintf(":%d", config.Config.HTTPPort), config.Config.SSLCertFile, config.Config.SSLPrivateKeyFile, m)
		if err != nil {
			log.Fatale(err)
		}
	} else {
		nethttp.ListenAndServe(fmt.Sprintf(":%d", config.Config.HTTPPort), m)
	}
}
开发者ID:grierj,项目名称:orchestrator-agent,代码行数:34,代码来源:http.go

示例6: mount

func mount(war string) {

	m := martini.Classic()
	m.Handlers(martini.Recovery())
	m.Use(gzip.All())
	m.Use(martini.Static(war, martini.StaticOptions{SkipLogging: true}))
	//    m.Use(render.Renderer(render.Options{
	//        Extensions: []string{".html", ".shtml"},
	//    }))
	//	m.Use(render.Renderer())
	//    m.Use(midTextDefault)

	//map web
	m.Use(func(w http.ResponseWriter, c martini.Context) {
		web := &Web{w: w}
		c.Map(web)
	})

	m.Group("/test", func(api martini.Router) {
		api.Get("", mainHandler)
		api.Get("/1", test1Handler)
		api.Get("/2", test2Handler)
	})

	http.Handle("/", m)
}
开发者ID:gavinzhs,项目名称:laohuo_process,代码行数:26,代码来源:mount.go

示例7: NewWebService

// NewWebService creates a new web service ready to run.
func NewWebService() *martini.Martini {
	m := martini.New()
	m.Handlers(loggerMiddleware(), martini.Recovery(), gzip.All())
	r := newRouter()
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)
	return m
}
开发者ID:PepperSalt42,项目名称:api,代码行数:9,代码来源:http.go

示例8: Http

// Http starts serving HTTP (api/web) requests
func Http() {
	martini.Env = martini.Prod
	m := martini.Classic()
	if config.Config.HTTPAuthUser != "" {
		m.Use(auth.Basic(config.Config.HTTPAuthUser, config.Config.HTTPAuthPassword))
	}

	m.Use(gzip.All())
	// Render html templates from templates directory
	m.Use(render.Renderer(render.Options{
		Directory:       "resources",
		Layout:          "templates/layout",
		HTMLContentType: "text/html",
	}))
	m.Use(martini.Static("resources/public"))
	if config.Config.UseMutualTLS {
		m.Use(ssl.VerifyOUs(config.Config.SSLValidOUs))
	}

	go agent.ContinuousOperation()

	log.Infof("Starting HTTP on port %d", config.Config.HTTPPort)

	http.API.RegisterRequests(m)

	listenAddress := fmt.Sprintf(":%d", config.Config.HTTPPort)

	// Serve
	if config.Config.UseSSL {
		if len(config.Config.SSLCertFile) == 0 {
			log.Fatale(errors.New("UseSSL is true but SSLCertFile is unspecified"))
		}

		if len(config.Config.SSLPrivateKeyFile) == 0 {
			log.Fatale(errors.New("UseSSL is true but SSLPrivateKeyFile is unspecified"))
		}

		log.Info("Starting HTTPS listener")
		tlsConfig, err := ssl.NewTLSConfig(config.Config.SSLCAFile, config.Config.UseMutualTLS)
		if err != nil {
			log.Fatale(err)
		}
		if err = ssl.AppendKeyPair(tlsConfig, config.Config.SSLCertFile, config.Config.SSLPrivateKeyFile); err != nil {
			log.Fatale(err)
		}
		if err = ssl.ListenAndServeTLS(listenAddress, m, tlsConfig); err != nil {
			log.Fatale(err)
		}
	} else {
		log.Info("Starting HTTP listener")
		if err := nethttp.ListenAndServe(listenAddress, m); err != nil {
			log.Fatale(err)
		}
	}
	log.Info("Web server started")
}
开发者ID:BrianIp,项目名称:orchestrator-agent,代码行数:57,代码来源:http.go

示例9: main

func main() {
	fmt.Println("hello")
	go freeAlloc()
	m := martini.Classic()
	m.Handlers(gzip.All(), martini.Recovery())
	Mount(m, 100)
	log.Printf("start gateway on %s\n", 5050)

	log.Fatal(http.ListenAndServe(":5050", nil))
//	m.RunOnAddr(":5050")
}
开发者ID:xiaotiejiang888,项目名称:goPraticse,代码行数:11,代码来源:main.go

示例10: init

func init() {
	// BASE_URL, AUTH_USER and AUTH_PASS, AWS_S3_BASE_URL are not required or else wercker tests would fail
	baseURL = os.Getenv("BASE_URL")
	authUser = os.Getenv("AUTH_USER")
	authPass = os.Getenv("AUTH_PASS")
	s3BaseURL = os.Getenv("AWS_S3_BASE_URL")

	if awsAuth, err := aws.EnvAuth(); err != nil {
		// not required or else wercker tests would fail
		log.Println(err)
	} else {
		// TODO(jrubin) allow region to be chosen by env variable
		s3Data := s3.New(awsAuth, aws.USWest2)
		s3Bucket = s3Data.Bucket(os.Getenv("AWS_S3_BUCKET_NAME"))
	}

	m = martini.Classic()

	m.Use(gzip.All())
	m.Use(render.Renderer())

	m.Get("/", func() string {
		return "hello, world"
	})

	m.Post(
		"/v1/transcribe",
		auth.Basic(authUser, authPass),
		strict.Accept("application/json"),
		strict.ContentType("application/x-www-form-urlencoded"),
		binding.Bind(transcribeData{}),
		binding.ErrorHandler,
		handleTranscribe,
	)

	m.Post(
		"/v1/transcribe/process",
		strict.ContentType("application/x-www-form-urlencoded"),
		binding.Bind(telapi.TranscribeCallbackData{}),
		binding.ErrorHandler,
		handleTranscribeProcess,
	)

	m.Post(
		"/v1/transcribe/upload",
		auth.Basic(authUser, authPass),
		strict.Accept("application/json"),
		binding.MultipartForm(transcribeUploadData{}),
		binding.ErrorHandler,
		handleTranscribeUpload,
	)

	m.Router.NotFound(strict.MethodNotAllowed, strict.NotFound)
}
开发者ID:joshuarubin,项目名称:goscribe,代码行数:54,代码来源:web.go

示例11: NewApiServer

func NewApiServer() http.Handler {
	m := martini.New()
	m.Use(martini.Recovery())
	m.Use(render.Renderer())
	m.Use(func(w http.ResponseWriter, req *http.Request, c martini.Context) {
		path := req.URL.Path
		if req.Method == "GET" && strings.HasPrefix(path, "/") {
			var remoteAddr = req.RemoteAddr
			var headerAddr string
			for _, key := range []string{"X-Real-IP", "X-Forwarded-For"} {
				if val := req.Header.Get(key); val != "" {
					headerAddr = val
					break
				}
			}
			fmt.Printf("API call %s from %s [%s]\n", path, remoteAddr, headerAddr)
			//if ip := strings.Split(remoteAddr,":");ip[0] != "172.17.140.52" {
			//	w.WriteHeader(404)
			//	return
			//}
		}
		c.Next()
	})
	api := &apiServer{Version: "1.00", Compile: "go"}
	api.Load()
	api.StartDaemonRoutines()
	m.Use(gzip.All())
	m.Use(func(req *http.Request, c martini.Context, w http.ResponseWriter) {
		if req.Method == "GET" && strings.HasPrefix(req.URL.Path, "/teampickwrwithoutjson") {
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
		} else {
			w.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
			w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型
			w.Header().Set("Content-Type", "application/json; charset=utf-8")
		}
	})
	r := martini.NewRouter()
	r.Get("/", func(r render.Render) {
		r.Redirect("/overview")
	})
	r.Get("/overview", api.showOverview)
	r.Get("/fetch/:account_id", api.fetchId)
	r.Get("/fetchupdate", api.fetchUpdate)
	r.Get("/teampick/:herolist", api.teamPick)
	r.Get("/teampickwr/:herolist", api.teamPickWinRate)
	r.Get("/teampickwrwithoutjson/:herolist", api.teamPickWinRateWithoutJSON)
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)
	return m
}
开发者ID:tedcy,项目名称:DotaTeamPicker,代码行数:50,代码来源:api_server.go

示例12: main

func main() {
	var config, port, api string

	flag.StringVar(&config, "c", "config.json", "Config file")
	flag.StringVar(&port, "p", "8080", "Port")
	flag.StringVar(&api, "a", "DEFAULT", "API key")

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, `Usage: %s [options]

Barycenter serves a JSON configuration file over HTTP
using basic authentication (so run it over SSL).

Run an endpoint as follows:

  %s -c config.json -a DEFAULT -p 8080

You can then make a request against the endpoint.

  curl -u DEFAULT: 127.0.0.1:8080

OPTIONS:
`, os.Args[0], os.Args[0])
		flag.PrintDefaults()
	}

	flag.Parse()

	if flag.NArg() != 0 {
		flag.Usage()
		os.Exit(1)
	}

	json, err := ioutil.ReadFile(config)
	if err != nil {
		log.Fatalf("Could not read configuration: %s", err)
	}

	m := martini.Classic()
	m.Use(gzip.All())
	m.Use(auth.Basic(api, ""))

	m.Get("/", func(w http.ResponseWriter, req *http.Request) string {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		return string(json)
	})

	http.ListenAndServe(":"+port, m)
}
开发者ID:ralreegorganon,项目名称:barycenter,代码行数:49,代码来源:main.go

示例13: main

func main() {
	m := martini.Classic()

	//Make sure to include the Gzip middleware above other middleware that alter the response body (like the render middleware).
	m.Use(gzip.All())

	// render html templates from templates directory
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))

	controllers.RouterInit(m)

	m.Run()
}
开发者ID:Zxnui,项目名称:go-martini-test,代码行数:15,代码来源:main.go

示例14: main

func main() {
	var serverPort int
	var localhost bool

	flag.StringVar(&ledgerFileName, "f", "", "Ledger file name (*Required).")
	flag.StringVar(&reportConfigFileName, "r", "", "Report config file name (*Required).")
	flag.IntVar(&serverPort, "port", 8056, "Port to listen on.")
	flag.BoolVar(&localhost, "localhost", false, "Listen on localhost only.")

	flag.Parse()

	if len(ledgerFileName) == 0 || len(reportConfigFileName) == 0 {
		flag.Usage()
		return
	}

	go func() {
		for {
			var rLoadData reportConfigStruct
			toml.DecodeFile(reportConfigFileName, &rLoadData)
			reportConfigData = rLoadData
			time.Sleep(time.Minute * 5)
		}
	}()

	m := martini.Classic()
	m.Use(gzip.All())
	m.Use(staticbin.Static("public", Asset))

	m.Get("/ledger", ledgerHandler)
	m.Get("/accounts", accountsHandler)
	m.Get("/account/:accountName", accountHandler)
	m.Get("/report/:reportName", reportHandler)
	m.Get("/", func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, "/accounts", http.StatusFound)
	})

	fmt.Println("Listening on port", serverPort)
	listenAddress := ""
	if localhost {
		listenAddress = fmt.Sprintf("127.0.0.1:%d", serverPort)
	} else {
		listenAddress = fmt.Sprintf(":%d", serverPort)
	}
	http.ListenAndServe(listenAddress, m)
}
开发者ID:howeyc,项目名称:ledger,代码行数:46,代码来源:main.go

示例15: setupMartini

func setupMartini(db *sql.DB, conf *config.Config, mediaManager *media.Manager) {
	m := martini.Classic()

	m.Use(auth.SpecAuth(conf.Auth.Username, conf.Auth.Password, conf.Auth.ApiPath))
	m.Use(gzip.All())

	m.Map(db)

	m.Map(conf)

	m.Map(mediaManager)

	rendererOption := render.Options{
		Layout: "layout",
		Funcs: []htmlTemplate.FuncMap{
			{
				"echoActiveLink":     blahTemplate.EchoActiveLink,
				"echoPageAction":     blahTemplate.EchoPageAction,
				"echoSelectSelected": blahTemplate.EchoSelectSelected,
				"echoMediaUpload":    blahTemplate.EchoMediaUpload,
				"echoMediaDisplay":   blahTemplate.EchoMediaDisplay,
				"echoTimestamp":      blahTemplate.EchoTimeStamp,
				"echoLanguage":       blahTemplate.EchoLanguage,
			},
		},
		IndentJSON: true,
	}

	m.Use(render.Renderer(rendererOption))

	entity.SetMediaBaseUrl(conf.Blah.BaseMediaUri)

	blahTemplate.Module(m)

	controller.Module(m, conf.Auth.ApiPath)

	m.Get("/", ShowWelcome)

	m.Run()
}
开发者ID:peteraba,项目名称:go-blah,代码行数:40,代码来源:main.go


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