本文整理匯總了Golang中github.com/gin-gonic/gin.BasicAuth函數的典型用法代碼示例。如果您正苦於以下問題:Golang BasicAuth函數的具體用法?Golang BasicAuth怎麽用?Golang BasicAuth使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了BasicAuth函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Serve
func Serve(address, dbpath string) {
DBInit(dbpath)
AccountsInit()
route := gin.Default()
route.GET("/", Index)
route.LoadHTMLGlob("templates/*.html")
product := route.Group("/product", gin.BasicAuth(ACCOUNT))
{
product.GET(":id", getProduct)
product.GET("", queryProduct)
product.POST("", updateProduct)
product.POST(":id", updateProduct)
product.DELETE(":id", deleteProduct)
}
series := route.Group("/series", gin.BasicAuth(ACCOUNT))
{
series.POST("", addSeries)
}
validate := route.Group("/v")
{
validate.GET(":id", getSerie)
validate.POST(":id", claimSerie)
}
route.Static("/static", "static")
route.Static("/asset", "asset")
route.Run(address)
}
示例2: main
func main() {
r := gin.Default()
// Group using gin.BasicAuth() middleware
// gin.Accounts is a shortcut for map[string]string
authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
"foo": "bar",
"austin": "1234",
"lena": "hello2",
"manu": "4321",
}))
// /admin/secrets endpoint
// hit "localhost:8080/admin/secrets
authorized.GET("/secrets", func(c *gin.Context) {
// get user, it was setted by the BasicAuth middleware
user := c.MustGet(gin.AuthUserKey).(string)
if secret, ok := secrets[user]; ok {
c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})
} else {
c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})
}
})
// Listen and server on 0.0.0.0:8080
r.Run(":8080")
}
示例3: startHTTP
func startHTTP() {
log.Printf("Starting server on %s", gConfig.Host)
router := gin.Default()
if gConfig.HasAuth() {
router.Use(gin.BasicAuth(gin.Accounts{gConfig.UI.Username: gConfig.UI.Password}))
}
router.Use(gitserverHandler())
if gConfig.EnableCORS {
router.Use(corsHandler())
}
if !gConfig.UI.DisableUI {
router.StaticFS(gConfig.Repos.Path, http.Dir("./public/"))
}
router.GET("/", handler)
api.SetupRouter(router)
if einhorn.IsRunning() {
einhorn.Start(router, 0)
} else {
router.Run(gConfig.Host)
}
}
示例4: main
func main() {
flag.Parse()
if showv {
showVersion()
return
}
appConfig, err := config.LoadAppConfig(conf)
if err != nil {
fmt.Printf("config load err: %s\n", err)
os.Exit(-1)
}
if !debug {
gin.SetMode(gin.ReleaseMode)
}
r := gin.Default()
r.Static("/assets", "./ui/assets")
r.LoadHTMLGlob("ui/templates/*")
r.Use(appConfigMiddleware(appConfig))
if appConfig.Basic_auth.On {
r.Use(gin.BasicAuth(gin.Accounts{appConfig.Basic_auth.Username: appConfig.Basic_auth.Password}))
}
r.GET("/", controller.Home)
r.GET("/node", controller.Node)
r.GET("/cluster", controller.Cluster)
r.POST("/do", controller.Do)
r.Run(listen)
}
示例5: Listen
// Listen Tells Gin API to start
func Listen(iface string, s *discordgo.Session, logger *logging.Logger) {
// set the refs to point to main
var v1 *gin.RouterGroup
session = s
c := config.Get()
log = logger
if c.LogLevel != "debug" {
gin.SetMode(gin.ReleaseMode)
}
//r := gin.Default()
r := gin.New()
r.Use(loggerino())
r.Use(gin.Recovery())
if c.APIPassword != "" {
log.Info("Basic Authentication enabled for API")
v1 = r.Group("/v1", gin.BasicAuth(gin.Accounts{
c.APIUsername: c.APIPassword,
}))
} else {
log.Warning("DIGO_API_PASSWORD and DIGO_API_USERNAME are not set")
log.Warning("The API is open to all requests")
v1 = r.Group("/v1")
}
v1.GET("/version", versionV1)
v1.GET("/channels", channelsV1)
v1.POST("/message", messageV1)
go r.Run(iface)
log.Noticef("Digo API is listening on %s", c.APIInterface)
}
示例6: TestLogRequest
func TestLogRequest(t *testing.T) {
s := loadServerCtx()
s.AllowedApps = append(s.AllowedApps, "test")
s.AppPasswd["test"] = "pass"
s.in = make(chan *logData)
defer close(s.in)
s.out = make(chan *logMetrics)
defer close(s.out)
go logProcess(s.in, s.out)
r := gin.New()
auth := r.Group("/", gin.BasicAuth(s.AppPasswd))
auth.POST("/", s.processLogs)
req, _ := http.NewRequest("POST", "/", bytes.NewBuffer([]byte("LINE of text\nAnother line\n")))
req.SetBasicAuth("test", "pass")
resp := httptest.NewRecorder()
r.ServeHTTP(resp, req)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Error(err)
}
if string(body) != "OK" {
t.Error("resp body should match")
}
if resp.Code != 200 {
t.Error("should get a 200")
}
}
示例7: main
func main() {
gin.SetMode(gin.ReleaseMode)
s := loadServerCtx()
if s.Debug {
log.SetLevel(log.DebugLevel)
gin.SetMode(gin.DebugMode)
}
c, err := statsdClient(s.StatsdUrl)
if err != nil {
log.WithField("statsdUrl", s.StatsdUrl).Fatal("Could not connect to statsd")
}
r := gin.Default()
r.GET("/status", func(c *gin.Context) {
c.String(200, "OK")
})
if len(s.AppPasswd) > 0 {
auth := r.Group("/", gin.BasicAuth(s.AppPasswd))
auth.POST("/", s.processLogs)
}
s.in = make(chan *logData, bufferLen)
defer close(s.in)
s.out = make(chan *logMetrics, bufferLen)
defer close(s.out)
go logProcess(s.in, s.out)
go c.sendToStatsd(s.out)
log.Infoln("Server ready ...")
r.Run(":" + s.Port)
}
示例8: Monitor
func (s schedule) Monitor(e *gin.Engine, path, username, password string) schedule {
r := e.RouterGroup
m := gin.Accounts{
username: password,
}
r.Use(gin.BasicAuth(m))
r.GET(path, JobHtml)
return s
}
示例9: Run
func (s *Service) Run() error {
eng := gin.Default()
eng.LoadHTMLGlob(s.Config.App.TemplatesPath + "/*")
eng.Static("/assets", s.Config.App.AssetPath)
prefix := "/"
if s.Config.App.Prefix != "" {
prefix = s.Config.App.Prefix
}
g := eng.Group(prefix, gin.BasicAuth(gin.Accounts{
s.Config.Admin.Login: s.Config.Admin.Password,
}))
g.GET("/", func(c *gin.Context) {
posts, e := s.Store.GetSlice(10, 0)
res := gin.H{}
if e != nil {
fmt.Println(e)
res["error"] = e
}
res["posts"] = posts
c.HTML(200, "index.html", res)
})
g.Any("/create", func(c *gin.Context) {
rm := gin.H{}
if c.Request.Method == "POST" {
rm["message"] = "posted"
title := c.PostForm("title")
content := c.PostForm("content")
p := new(Post)
p.Title = title
p.Body = content
e := s.Store.Save(p)
if e != nil {
fmt.Println(e)
rm["error"] = e
}
}
c.HTML(200, "edit.html", rm)
})
g.GET("/p/:id", func(c *gin.Context) {
id := c.Param("id")
c.HTML(200, "show.html", gin.H{"da": id})
})
g.POST("/p/:id", func(c *gin.Context) {
})
return http.ListenAndServe(fmt.Sprintf(":%d", s.Config.App.Port), eng)
}
示例10: Start
func (s *Server) Start() {
r := gin.Default()
r.StaticFS("/data", http.Dir(filepath.Join(s.FpRoot, "data")))
r.StaticFS("/assets", http.Dir("./assets"))
var api, ui gin.IRoutes
if s.AdminUser != "" {
accounts := gin.Accounts{s.AdminUser: s.AdminPass}
api = r.Group("/api", gin.BasicAuth(accounts))
ui = r.Group("/ui", gin.BasicAuth(accounts))
} else {
api = r.Group("/api")
ui = r.Group("/ui")
}
{
api.POST("/upload/:hash", s.upload)
api.POST("/nonexists", s.nonexists)
api.GET("/stat", s.stat)
api.GET("/tags", s.indexTags)
api.GET("/tags/:id", s.getTags)
api.POST("/tags/:id", s.postTags)
api.GET("/tags/:id/files/*path", s.getTagsFile)
api.GET("/tags/:id/versions", s.indexTagsVersions)
}
ui.GET("/*dummy", func(c *gin.Context) {
file, err := ioutil.ReadFile("./assets/index.html")
if err != nil {
c.AbortWithError(500, err)
return
}
c.Data(200, "text/html", file)
})
// redirect _admin/* to api/*
r.Any("/_admin/*path", func(c *gin.Context) {
c.Request.URL.Path = "/api" + c.Param("path")
r.ServeHTTP(c.Writer, c.Request)
})
r.Run(fmt.Sprintf(":%d", s.Port))
}
示例11: startServer
func startServer() {
router := gin.Default()
// Enable HTTP basic authentication only if both user and password are set
if options.AuthUser != "" && options.AuthPass != "" {
auth := map[string]string{options.AuthUser: options.AuthPass}
router.Use(gin.BasicAuth(auth))
}
router.GET("/", APIHome)
router.POST("/connect", APIConnect)
router.DELETE("/disconnect", APIClose)
router.GET("/databases", APIGetDatabases)
router.GET("/databases/:database/tables", APIGetDatabaseTables)
router.GET("/databases/:database/tables/:table/column", APIGetColumnOfTable)
router.GET("/databases/:database/views", APIGetDatabaseViews)
router.GET("/databases/:database/procedures", APIGetDatabaseProcedures)
router.GET("/databases/:database/functions", APIGetDatabaseFunctions)
router.POST("/databases/:database/actions/default", APISetDefaultDatabase)
router.GET("/info", APIInfo)
router.GET("/tables/:table/info", APIGetTableInfo)
router.GET("/tables/:table/indexes", APITableIndexes)
router.GET("/query", APIRunQuery)
router.POST("/query", APIRunQuery)
router.GET("/explain", APIExplainQuery)
router.POST("/explain", APIExplainQuery)
router.GET("/history", APIHistory)
router.GET("/static/:type/:name", APIServeAsset)
router.GET("/procedures/:procedure/parameters", APIProcedureParameters)
router.GET("/collation", APIGetCollationCharSet)
router.POST("/databases/:database/actions/alter", APIAlterDatabase)
router.DELETE("/databases/:database/actions/drop", APIDropDatabase)
router.DELETE("/databases/:database/tables/:table/actions/drop", APIDropTable)
router.DELETE("/databases/:database/tables/:table/actions/truncate", APITruncateTable)
router.GET("/databases/:database/procedures/:procedure", APIProcedureDefinition)
router.GET("/databases/:database/functions/:function", APIFunctionDefinition)
router.POST("/databases/:database/procedures/:procedure", APICreateProcedure)
router.POST("/databases/:database/functions/:function", APICreateFunction)
router.DELETE("/databases/:database/procedures/:procedure/actions/drop", APIDropProcedure)
router.GET("/databases/:database/views/:view", APIViewDefinition)
router.GET("/search/:query", apiSearch)
router.GET("/bookmarks", APIGetBookmarks)
router.POST("/bookmarks/:name", APISaveBookmark)
router.DELETE("/bookmarks/:name", APIDeleteBookmark)
router.GET("/updates", getUpdate)
fmt.Println("Starting server...")
go router.Run(fmt.Sprintf("%v:%v", options.HttpHost, options.HttpPort))
}
示例12: main
func main() {
r := gin.Default()
// Ping test
r.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
// Get user value
r.GET("/user/:name", func(c *gin.Context) {
user := c.Params.ByName("name")
value, ok := DB[user]
if ok {
c.JSON(200, gin.H{"user": user, "value": value})
} else {
c.JSON(200, gin.H{"user": user, "status": "no value"})
}
})
// Authorized group (uses gin.BasicAuth() middleware)
// Same than:
// authorized := r.Group("/")
// authorized.Use(gin.BasicAuth(gin.Credentials{
// "foo": "bar",
// "manu": "123",
//}))
authorized := r.Group("/", gin.BasicAuth(gin.Accounts{
"foo": "bar", // user:foo password:bar
"manu": "123", // user:manu password:123
}))
authorized.POST("admin", func(c *gin.Context) {
user := c.MustGet(gin.AuthUserKey).(string)
// Parse JSON
var json struct {
Value string `json:"value" binding:"required"`
}
if c.Bind(&json) {
DB[user] = json.Value
c.JSON(200, gin.H{"status": "ok"})
}
})
// Listen and Server in 0.0.0.0:8080
r.Run(":8080")
}
示例13: RegistrarRotas
// RegistrarRotas realiza o registro de todas as rotas da aplicação.
func RegistrarRotas(r *gin.Engine, usuario, senha string) {
// Habilitando esquema de autorização simples
auth := r.Group("/", gin.BasicAuth(gin.Accounts{usuario: senha}))
auth.GET("/", Raiz)
auth.GET("/pagina/:pag", Pagina)
auth.GET("/formulario", Formulario)
auth.POST("/salvar", Salvar)
auth.GET("/remover/:id", Remover)
auth.GET("/editar/:id", Editar)
}
示例14: Run
func (s *TwitterService) Run(cfg Config) error {
s.Migrate(cfg)
db, err := s.getDb(cfg)
if err != nil {
return err
}
db.SingularTable(true)
twitterResource := &TwitterResource{db: db}
r := gin.Default()
//gin.SetMode(gin.ReleaseMode)
r.Use(cors.Middleware(cors.Options{}))
ba := r.Group("/", gin.BasicAuth(gin.Accounts{
"paul": "1234",
"ming": "1234",
}))
ba.GET("/twitter", twitterResource.GetAllTwitters)
ba.GET("/twitter/:id", twitterResource.GetTwitter)
ba.POST("/twitter", twitterResource.CreateTwitter)
ba.PUT("/twitter/:id", twitterResource.UpdateTwitter)
ba.PATCH("/twitter/:id", twitterResource.PatchTwitter)
ba.DELETE("/twitter/:id", twitterResource.DeleteTwitter)
//for user
ba.GET("/user", twitterResource.GetAllUsers)
ba.GET("/user/:id", twitterResource.GetUser)
ba.POST("/user", twitterResource.CreateUser)
ba.PUT("/user/:id", twitterResource.UpdateUser)
ba.PATCH("/user/:id", twitterResource.PatchUser)
ba.DELETE("/user/:id", twitterResource.DeleteUser)
//user+twitter
ba.POST("/twitter/user/:id", twitterResource.CreateTwitterByUserId)
ba.GET("/user/:id/twitter", twitterResource.GetTwittersByUserId)
r.Run(cfg.SvcHost)
return nil
}
示例15: main
func main() {
r := gin.Default()
r.Use(gzip.Gzip(gzip.DefaultCompression))
// Group using gin.BasicAuth() middleware
authorized := r.Group("/")
if len(config.Accounts) > 0 {
authorized.Use(gin.BasicAuth(config.Accounts))
}
for _, f := range config.StaticFS {
authorized.StaticFS("/"+f, http.Dir(f))
}
authorized.GET(config.HomeUrl, func(c *gin.Context) {
c.JSON(http.StatusOK, "home!")
})
r.Run(config.ListenAddress)
}