本文整理汇总了Golang中github.com/martini-contrib/auth.Basic函数的典型用法代码示例。如果您正苦于以下问题:Golang Basic函数的具体用法?Golang Basic怎么用?Golang Basic使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Basic函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
}
示例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)
}
示例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)
}
示例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()
}
示例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)
}
}
示例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)
}
}
示例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")
}
示例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()
}
示例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))
}
}
示例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()
}
示例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")
}
示例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")
}
示例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)
}
示例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)
}
示例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()
}