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

Golang gzip.All函数代码示例

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

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



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


示例16: agentsHttp

// agentsHttp startes serving agents API requests
func agentsHttp() {
	m := martini.Classic()
	m.Use(gzip.All())
	m.Use(render.Renderer())

	log.Info("Starting agents HTTP")

	go logic.ContinuousAgentsPoll()

	http.AgentsAPI.RegisterRequests(m)

	// Serve
	if config.Config.AgentsUseSSL {
		log.Info("Serving via SSL")
		err := nethttp.ListenAndServeTLS(":3001", config.Config.SSLCertFile, config.Config.SSLPrivateKeyFile, m)
		if err != nil {
			log.Fatale(err)
		}
	} else {
		nethttp.ListenAndServe(":3001", m)
	}
}
开发者ID:shuhaowu,项目名称:orchestrator,代码行数:23,代码来源:http.go


示例17: agentsHttp

// agentsHttp startes serving agents HTTP or HTTPS API requests
func agentsHttp() {
	m := martini.Classic()
	m.Use(gzip.All())
	m.Use(render.Renderer())
	if config.Config.AgentsUseMutualTLS {
		m.Use(ssl.VerifyOUs(config.Config.AgentSSLValidOUs))
	}

	log.Info("Starting agents listener")

	agent.InitHttpClient()
	go logic.ContinuousAgentsPoll()

	http.AgentsAPI.URLPrefix = config.Config.URLPrefix
	http.AgentsAPI.RegisterRequests(m)

	// Serve
	if config.Config.AgentsUseSSL {
		log.Info("Starting agent HTTPS listener")
		tlsConfig, err := ssl.NewTLSConfig(config.Config.AgentSSLCAFile, config.Config.AgentsUseMutualTLS)
		if err != nil {
			log.Fatale(err)
		}
		tlsConfig.InsecureSkipVerify = config.Config.AgentSSLSkipVerify
		if err = ssl.AppendKeyPairWithPassword(tlsConfig, config.Config.AgentSSLCertFile, config.Config.AgentSSLPrivateKeyFile, agentSSLPEMPassword); err != nil {
			log.Fatale(err)
		}
		if err = ssl.ListenAndServeTLS(config.Config.AgentsServerPort, m, tlsConfig); err != nil {
			log.Fatale(err)
		}
	} else {
		log.Info("Starting agent HTTP listener")
		if err := nethttp.ListenAndServe(config.Config.AgentsServerPort, m); err != nil {
			log.Fatale(err)
		}
	}
	log.Info("Agent server started")
}
开发者ID:enisoc,项目名称:orchestrator,代码行数:39,代码来源:http.go


示例18: NewApi

func NewApi() *martini.Martini {
	m := martini.New()

	// Setup middleware
	m.Use(martini.Recovery())
	m.Use(martini.Logger())
	m.Use(gzip.All())
	m.Use(func(w http.ResponseWriter, req *http.Request) {
		if req.URL.Path != "/mtg/cards/random" {
			w.Header().Set("Cache-Control", "public,max-age=3600")
		}
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("License", "The textual information presented through this API about Magic: The Gathering is copyrighted by Wizards of the Coast.")
		w.Header().Set("Disclaimer", "This API is not produced, endorsed, supported, or affiliated with Wizards of the Coast.")
		w.Header().Set("Pricing", "store.tcgplayer.com allows you to buy cards from any of our vendors, all at the same time, in a simple checkout experience. Shop, Compare & Save with TCGplayer.com!")
		w.Header().Set("Strict-Transport-Security", "max-age=86400")
	})

	r := martini.NewRouter()

	r.Get("/ping", Ping)
	r.Get("/mtg/cards", HandleCards)
	r.Get("/mtg/cards/typeahead", HandleTypeahead)
	r.Get("/mtg/cards/random", HandleRandomCard)
	r.Get("/mtg/cards/:id", HandleCard)
	r.Get("/mtg/sets", HandleSets)
	r.Get("/mtg/sets/:id", HandleSet)
	r.Get("/mtg/colors", HandleTerm("colors"))
	r.Get("/mtg/supertypes", HandleTerm("supertypes"))
	r.Get("/mtg/subtypes", HandleTerm("subtypes"))
	r.Get("/mtg/types", HandleTerm("types"))
	r.NotFound(NotFound)

	m.Action(r.Handle)
	return m
}
开发者ID:ZachWilson130,项目名称:deckbrew-api,代码行数:37,代码来源:api.go


示例19: main

func main() {
	store.Setup()

	m := martini.New()
	router := martini.NewRouter()

	router.NotFound(func() (int, []byte) {
		return 404, []byte("Requested page not found.")
	})

	m.Use(martini.Logger())
	m.Use(martini.Recovery())
	m.Use(gzip.All())

	m.Use(func(c martini.Context, w http.ResponseWriter) {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	})

	router.Group("/chats", func(r martini.Router) {
		r.Get("/userchats/:userid", chat.GetChats)       // Get list of all chats for a user
		r.Get("/messages/:chatid", chat.ViewMessages)    // View chat messages for a chat
		r.Post("/newchat", chat.NewChat)                 // Create a new chat with specific users
		r.Post("/sendmessage/:chatid", chat.SendMessage) // Send message to a chat as a user
	})

	router.Group("/users", func(r martini.Router) {
		r.Get("/get", users.GetUsers)               // Get list of all users
		r.Get("/new/:userName", users.NewUser)      // Make a new user
		r.Post("/delete/:userid", users.DeleteUser) // Delete a user with a specific id
	})

	m.MapTo(router, (*martini.Routes)(nil))
	m.Action(router.Handle)

	m.Run()
}
开发者ID:CyrusRoshan,项目名称:SampleChatBackend,代码行数:36,代码来源:main.go


示例20: standardHttp

// standardHttp starts serving HTTP or HTTPS (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"))
	if config.Config.UseMutualTLS {
		m.Use(ssl.VerifyOUs(config.Config.SSLValidOUs))
	}

	inst.SetMaintenanceOwner(process.ThisHostname)

	if discovery {
		log.Info("Starting Discovery")
		go logic.ContinuousDiscovery()
	}
	log.Info("Registering endpoints")
	http.API.RegisterRequests(m)
	http.Web.RegisterRequests(m)

	// Serve
	if config.Config.ListenSocket != "" {
		log.Infof("Starting HTTP listener on unix socket %v", config.Config.ListenSocket)
		unixListener, err := net.Listen("unix", config.Config.ListenSocket)
		if err != nil {
			log.Fatale(err)
		}
		defer unixListener.Close()
		if err := nethttp.Serve(unixListener, m); err != nil {
			log.Fatale(err)
		}
	} else if config.Config.UseSSL {
		log.Info("Starting HTTPS listener")
		tlsConfig, err := ssl.NewTLSConfig(config.Config.SSLCAFile, config.Config.UseMutualTLS)
		if err != nil {
			log.Fatale(err)
		}
		tlsConfig.InsecureSkipVerify = config.Config.SSLSkipVerify
		if err = ssl.AppendKeyPairWithPassword(tlsConfig, config.Config.SSLCertFile, config.Config.SSLPrivateKeyFile, sslPEMPassword); err != nil {
			log.Fatale(err)
		}
		if err = ssl.ListenAndServeTLS(config.Config.ListenAddress, m, tlsConfig); err != nil {
			log.Fatale(err)
		}
	} else {
		log.Infof("Starting HTTP listener on %+v", config.Config.ListenAddress)
		if err := nethttp.ListenAndServe(config.Config.ListenAddress, m); err != nil {
			log.Fatale(err)
		}
	}
	log.Info("Web server started")
}
开发者ID:BrianIp,项目名称:orchestrator,代码行数:89,代码来源:http.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang oauth2.Tokens类代码示例发布时间:2022-05-23
下一篇:
Golang encoder.Encoder类代码示例发布时间: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