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

Golang auth.Basic函数代码示例

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

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



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

示例1: 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


示例2: main

func main() {
	list := karambie.List()
	route := mux.NewRouter()       // use gorilla as router
	martini := martinihelper.New() // and also martini as middleware, see below

	currentDir, _ := os.Getwd()

	log := log.New(os.Stdout, "[Karambie] ", 0)

	logger := logger.New(log, false)                               // log every request
	recovery := recovery.New(log, nil)                             // recover if panic
	notfoundhandler := notfoundhandler.New(true, nil)              // show 404, add trailing slash to url if necessary
	static := static.New(filepath.Join(currentDir, "public"), log) // serve static file in folder "public"

	// register logger service for martini
	martini.Map(log)

	// the list is immutable, every calling to Add or AddFunc will create new list
	list = list.Add(logger, recovery)
	list = list.Add(karambie.Later(notfoundhandler))
	list = list.Add(karambie.Later(static))
	// or you can use karambie/middleware.Common() to build those list

	// list is [logger, recovery, notfoundhandler, static]
	// but the order of execution is [logger, recovery, static, notfoundhandler]
	// karambie.Later will create new handler that will be executed after succeeding handler
	// list processing will stop if one of them respond the request (http response status != 0)

	secureList := list.Add(martini.Conv(auth.Basic("user", "pass"))) // execution of secureList is [logger, recovery, auth, static, notfoundhandler]
	list = list.Add(martini.Conv(render.Renderer()))                 // execution of list is       [logger, recovery, render, static, notfoundhandler]
	// list != secureList, because it is immutable, every calling to Add or AddFunc will create new list

	// using http.HandlerFunc style
	route.Handle("/helloworld", list.AddFunc(hello)) // [logger, recovery, render, hello]
	// 'static' and 'notfoundhandler' will be ignored because 'hello' response the request

	// we can user list as NotFoundHandler (handle static file, and show error 404 if necessary)
	route.NotFoundHandler = list // [logger, recovery, static, notfoundhandler]
	// 'notfoundhandler' will be ignored if 'static' response the request

	// using martini.Handler style and gorilla routing
	route.Handle("/sayhi/{name}", list.Add(martini.Conv(sayhi))) // [logger, recovery, render, sayhi]

	// use secureList for sensitive resource
	route.Handle("/secret", secureList.AddFunc(secret)) // [logger, recovery, auth, secret]

	// add filterheader to list
	apiList := list.AddFunc(filterheader) // execution of apiList is [logger, recovery, filterheader, static, notfoundhandler]
	route.Handle("/api", apiList.AddFunc(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
		// this handler will not be called if 'filterheader' is not passed

		// get apikey
		ctx := karambie.Context(rw)
		key := ctx.Get("apikey").(string)

		fmt.Fprintln(rw, "Your api key : "+key)
	})))

	http.ListenAndServe(":3000", route)
}
开发者ID:win-t,项目名称:karambie,代码行数:60,代码来源:example.go


示例3: init

func init() {
	m = martini.New()

	//set up middleware
	m.Use(martini.Recovery())
	m.Use(martini.Logger())
	m.Use(auth.Basic(AuthToken, ""))
	m.Use(MapEncoder)

	// set up routes
	r := martini.NewRouter()
	r.Get(`/albums`, GetAlbums)
	r.Get(`/albums/:id`, GetAlbum)
	r.Post(`/albums`, AddAlbum)
	r.Put(`/albums/:id`, UpdateAlbum)
	r.Delete(`/albums/:id`, DeleteAlbum)

	// inject database
	// maps db package variable to the DB interface defined in data.go
	// The syntax for the second parameter may seem weird,
	// it is just converting nil to the pointer-to-DB-interface type,
	// because all the injector needs is the type to map the first parameter to.
	m.MapTo(db, (*DB)(nil))

	// add route action
	// adds the router’s configuration to the list of handlers that Martini will call.
	m.Action(r.Handle)
}
开发者ID:pyanfield,项目名称:martini_demos,代码行数:28,代码来源:server.go


示例4: standardHttp

// standardHttp starts serving standard HTTP (api/web) requests, to be used by normal clients
func standardHttp(discovery bool) {
	m := martini.Classic()
	if config.Config.HTTPAuthUser != "" {
		m.Use(auth.Basic(config.Config.HTTPAuthUser, config.Config.HTTPAuthPassword))
	}

	// 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"))

	log.Info("Starting HTTP")

	if discovery {
		go orchestrator.ContinuousDiscovery()
	}

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

	// Serve
	m.Run()
}
开发者ID:nandudheeraj,项目名称:orchestrator,代码行数:27,代码来源:http.go


示例5: 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


示例6: 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


示例7: 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


示例8: main

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

	baseGUID = os.Getenv("BASE_GUID")
	if baseGUID == "" {
		baseGUID = "29140B3F-0E69-4C7E-8A35"
	}
	serviceName = os.Getenv("SERVICE_NAME")
	if serviceName == "" {
		serviceName = "some-service-name" // replace with cfenv.AppName
	}
	servicePlan = os.Getenv("SERVICE_PLAN")
	if servicePlan == "" {
		servicePlan = "shared"
	}

	authUser = os.Getenv("AUTH_USER")
	authPassword = os.Getenv("AUTH_PASSWORD")
	if (authUser != "") && (authPassword != "") {
		// secure service broker with basic auth if both env variables are set
		m.Use(auth.Basic(authUser, authPassword))
	}

	serviceBinding.SyslogDrainURL = os.Getenv("SYSLOG_DRAIN_URL")

	credentials := os.Getenv("CREDENTIALS")
	if credentials == "" {
		credentials = "{\"port\": \"4000\"}"
	}
	tags = os.Getenv("TAGS")
	imageURL = os.Getenv("IMAGE_URL")

	json.Unmarshal([]byte(credentials), &serviceBinding.Credentials)
	fmt.Printf("%# v\n", pretty.Formatter(serviceBinding))

	appEnv, err := cfenv.Current()
	if err == nil {
		appURL = fmt.Sprintf("https://%s", appEnv.ApplicationURIs[0])
	} else {
		appURL = "http://localhost:5000"
	}
	fmt.Println("Running as", appURL)

	// Cloud Foundry Service API
	m.Get("/v2/catalog", brokerCatalog)
	m.Put("/v2/service_instances/:service_id", createServiceInstance)
	m.Delete("/v2/service_instances/:service_id", deleteServiceInstance)
	m.Put("/v2/service_instances/:service_id/service_bindings/:binding_id", createServiceBinding)
	m.Delete("/v2/service_instances/:service_id/service_bindings/:binding_id", deleteServiceBinding)

	// Service Instance Dashboard
	m.Get("/dashboard", showServiceInstanceDashboard)

	m.Run()
}
开发者ID:sergiubodiu,项目名称:worlds-simplest-service-broker,代码行数:55,代码来源:main.go


示例9: registerJobsRoutes

func (this *Server) registerJobsRoutes() {
	if config.GetConfig().Admin.UserName == "" {
		this.Martini.Group("/jobs", func(r martini.Router) {
			jobs_request.CreateJobsRoutes(r)
		})
	} else {
		this.Martini.Group("/jobs", func(r martini.Router) {
			jobs_request.CreateJobsRoutes(r)
		}, auth.Basic(config.GetConfig().Admin.UserName, config.GetConfig().Admin.Password))
	}

}
开发者ID:ArthurHlt,项目名称:microcos,代码行数:12,代码来源:server.go


示例10: main

func main() {
	// BasicAuth credentials for admin functions
	username := "user"
	password := "password"

	m := martini.Classic()

	//needs import ("time")
	m.Use(render.Renderer(render.Options{
		Directory: "templates",
		Layout:    "layout",
		Funcs: []template.FuncMap{
			{
				"formatTime": func(args ...interface{}) string {
					t1 := time.Time(args[0].(time.Time))
					return t1.Format("Jan 2, 2006 at 3:04pm (MST)")
				},
				"unescaped": func(args ...interface{}) template.HTML {
					return template.HTML(args[0].(string))
				},
			},
		},
	}))

	// Middleware for mongodb connection
	m.Use(Mongo())

	// Setup static file serving
	m.Use(martini.Static("assets"))

	// Setup routing
	m.Get("/", BlogEntryList)
	m.Post("/blog/add/submit", auth.Basic(username, password), binding.Form(dbBlogEntry{}), addBlogEntrySubmit)
	m.Get("/blog/add", auth.Basic(username, password), addBlogEntry)
	m.Get("/post/:Id", BlogEntry)
	m.Get("/about", About)
	m.Get("/impressum", Impressum)

	m.Run()
}
开发者ID:vanzswc,项目名称:blog,代码行数:40,代码来源:site.go


示例11: tSetup

func tSetup(output string) {
	tMux = http.NewServeMux()
	tServer = httptest.NewServer(tMux)
	m := martini.New()
	r := martini.NewRouter()
	r.Post("/transmission/rpc", func() string {
		return output
	})
	m.Action(r.Handle)
	m.Use(auth.Basic("test", "test"))
	tMux.Handle("/", m)

	transmissionClient = New(tServer.URL, "test", "test")
}
开发者ID:Tubbebubbe,项目名称:transmission,代码行数:14,代码来源:transmission_test.go


示例12: cSetup

func cSetup() {
	// test server
	cMux = http.NewServeMux()
	m := martini.New()
	r := martini.NewRouter()
	r.Post("/transmission/rpc", RPCHandler)
	m.Action(r.Handle)
	m.Use(auth.Basic("test", "test"))
	cMux.Handle("/", m)
	cServer = httptest.NewServer(cMux)

	// github client configured to use test server
	client = NewClient(cServer.URL+"/transmission/rpc", "test", "test")
}
开发者ID:pyed,项目名称:transmission,代码行数:14,代码来源:client_test.go


示例13: 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


示例14: Serve

// Serve sets everything up and runs the docker-builder server
func Serve(context *cli.Context) {
	// set vars
	setVarsFromContext(context)

	// set up auth functions
	if shouldBasicAuth {
		basicAuthFunc = auth.Basic(un, pwd)
	} else {
		basicAuthFunc = func(http.ResponseWriter, *http.Request) {}
	}
	if shouldTravisAuth {
		travisAuthFunc = vauth.TravisCI(travisToken)
	}
	if shouldGitHubAuth {
		githubAuthFunc = vauth.GitHub(githubSecret)
	}

	// configure webhooks
	webhook.Logger(logger)
	webhook.APIToken(apiToken)

	server = setupServer()

	if shouldTravis {
		server.Post(TravisRoute, travisAuthFunc, webhook.Travis)
	}
	if shouldGitHub {
		server.Post(GitHubRoute, githubAuthFunc, webhook.Github)
	}

	// base routes
	server.Get(HealthRoute, func() (int, string) { return 200, "200 OK" })
	server.Post(BuildRoute, basicAuthFunc, webhook.DockerBuild)

	// job control routes
	server.Group(JobRoute, func(r martini.Router) {
		r.Get("/:id", job.Get)
		r.Get("/:id/tail", job.TailN)
		r.Post("", webhook.DockerBuild)
		r.Get("", job.GetAll)
	}, basicAuthFunc)

	// start server
	http.ListenAndServe(portString, server)
}
开发者ID:carriercomm,项目名称:docker-builder,代码行数:46,代码来源:server.go


示例15: RunServer

func RunServer() {

	con := db.GetDbConn()
	defer con.Close()

	m := martini.Classic()
	m.Use(auth.Basic("kelly", "kelly"))
	m.Use(render.Renderer(render.Options{
		Directory: "templates",
		Layout:    "layout",
		Charset:   "UTF-8",
	}))

	m.Get("/", hello)
	m.Get("/create_user", createUserView)
	m.Post("/create_user", binding.Bind(NewUser{}), createUser)
	m.Run()
}
开发者ID:kelly-ry4n,项目名称:rpgmap,代码行数:18,代码来源:server.go


示例16: main

func main() {
	router := mux.NewRouter()

	router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"])
	})

	middle := interpose.New()

	// Use Martini-Auth, a Martini library for basic HTTP authentication
	middle.Use(adaptors.FromMartini(auth.Basic("user", "basic")))

	// Finally, add the router
	middle.UseHandler(router)

	// Now visit http://localhost:3001/guest and enter username "user"
	// and password "basic"
	http.ListenAndServe(":3001", middle)
}
开发者ID:RichardEby,项目名称:liveplant-server,代码行数:19,代码来源:main.go


示例17: App

func App(settings *Settings, DB *gorm.DB) *martini.ClassicMartini {

	m := martini.Classic()

	username := os.Getenv("AUTH_USER")
	password := os.Getenv("AUTH_PASS")

	m.Use(auth.Basic(username, password))
	m.Use(render.Renderer())

	m.Map(DB)
	m.Map(settings)

	log.Println("Loading Routes")

	// Serve the catalog with services and plans
	m.Get("/v2/catalog", func(r render.Render) {
		services := BuildCatalog()
		catalog := map[string]interface{}{
			"services": services,
		}
		r.JSON(200, catalog)
	})

	// Create the service instance (cf create-service-instance)
	m.Put("/v2/service_instances/:id", CreateInstance)

	// Bind the service to app (cf bind-service)
	m.Put("/v2/service_instances/:instance_id/service_bindings/:id", BindInstance)

	// Unbind the service from app
	m.Delete("/v2/service_instances/:instance_id/service_bindings/:id", func(p martini.Params, r render.Render) {
		var emptyJson struct{}
		r.JSON(200, emptyJson)
	})

	// Delete service instance
	m.Delete("/v2/service_instances/:id", DeleteInstance)

	return m
}
开发者ID:jinjing750629,项目名称:rds-broker,代码行数:41,代码来源:main.go


示例18: Init

func Init() (*martini.ClassicMartini, error) {
	m := martini.Classic()

	// set up our database
	db, err := database.Init()
	if err != nil {
		return nil, err
	}

	// database is available to handlers as *Database
	m.Map(db)

	// drops route
	m.Get("/drops", listDrops)
	m.Post("/drops", binding.MultipartForm(database.FormDrop{}), addDrop)
	// add regex for url+ to go to full size
	m.Get("/drops/:url", getDrop)
	m.Delete("/drops/:url", deleteDrop)

	m.Use(auth.Basic("zach", "zachorr"))
	m.Use(render.Renderer())
	return m, nil
}
开发者ID:ZachOrr,项目名称:dropzor,代码行数:23,代码来源:server.go


示例19: 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


示例20: withAuthOrNot

func withAuthOrNot() (authHandler martini.Handler) {
	if conf.Auth.Use {
		return auth.Basic(conf.Auth.Username, conf.Auth.Password)
	}
	return
}
开发者ID:tomzhang,项目名称:fuse,代码行数:6,代码来源:fuse.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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