本文整理汇总了Golang中github.com/cloudwan/gohan/util.GetConfig函数的典型用法代码示例。如果您正苦于以下问题:Golang GetConfig函数的具体用法?Golang GetConfig怎么用?Golang GetConfig使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了GetConfig函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestExtensions
// TestExtensions runs extension tests when invoked from Gohan CLI
func TestExtensions(c *cli.Context) {
buflog.SetUpDefaultLogging()
var config *util.Config
configFilePath := c.String("config-file")
if configFilePath != "" && !c.Bool("verbose") {
config = util.GetConfig()
err := config.ReadConfig(configFilePath)
if err != nil {
log.Error(fmt.Sprintf("Failed to read config from path %s: %v", configFilePath, err))
os.Exit(1)
}
err = gohan_log.SetUpLogging(config)
if err != nil {
log.Error(fmt.Sprintf("Failed to set up logging: %v", err))
os.Exit(1)
}
}
testFiles := getTestFiles(c.Args())
//logging from config is a limited printAllLogs option
returnCode := RunTests(testFiles, c.Bool("verbose") || config != nil, c.String("run-test"))
os.Exit(returnCode)
}
示例2: startSyncWatchProcess
//Sync Watch Process
func startSyncWatchProcess(server *Server) {
config := util.GetConfig()
watch := config.GetStringList("watch/keys", nil)
events := config.GetStringList("watch/events", nil)
if watch == nil {
return
}
extensions := map[string]extension.Environment{}
for _, event := range events {
path := "sync://" + event
env, err := server.NewEnvironmentForPath("sync."+event, path)
if err != nil {
log.Fatal(err.Error())
}
extensions[event] = env
}
responseChan := make(chan *gohan_sync.Event)
stopChan := make(chan bool)
for _, path := range watch {
go func(path string) {
defer util.LogFatalPanic(log)
for server.running {
lockKey := lockPath + "watch"
err := server.sync.Lock(lockKey, true)
if err != nil {
log.Warning("Can't start watch process due to lock", err)
time.Sleep(5 * time.Second)
continue
}
defer func() {
server.sync.Unlock(lockKey)
}()
err = server.sync.Watch(path, responseChan, stopChan)
if err != nil {
log.Error(fmt.Sprintf("sync watch error: %s", err))
}
}
}(path)
}
//main response lisnter process
go func() {
defer util.LogFatalPanic(log)
for server.running {
response := <-responseChan
server.queue.Add(job.NewJob(
func() {
defer util.LogPanic(log)
for _, event := range events {
//match extensions
if strings.HasPrefix(response.Key, "/"+event) {
env := extensions[event]
runExtensionOnSync(server, response, env.Clone())
return
}
}
}))
}
}()
}
示例3: getGraceServerCommand
func getGraceServerCommand() cli.Command {
return cli.Command{
Name: "glace-server",
ShortName: "gsrv",
Usage: "Run API Server with graceful restart support",
Description: "Run Gohan API server with graceful restart support",
Flags: []cli.Flag{
cli.StringFlag{Name: "config-file", Value: defaultConfigFile, Usage: "Server config File"},
},
Action: func(c *cli.Context) {
configFile := c.String("config-file")
loadConfig(configFile)
opts := &options{OptInterval: -1}
opts.OptCommand = os.Args[0]
config := util.GetConfig()
opts.OptPorts = []string{config.GetString("address", ":9091")}
opts.OptArgs = []string{"server", "--config-file", configFile}
s, err := starter.NewStarter(opts)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %s\n", err)
return
}
s.Run()
},
}
}
示例4: startAMQPProcess
//AMQP Process
func startAMQPProcess(server *Server) {
config := util.GetConfig()
enableAMQP := config.GetParam("amqp", nil)
if enableAMQP == nil {
return
}
listenAMQP(server)
}
示例5: startSNMPProcess
//SNMP Process
//Experimental
func startSNMPProcess(server *Server) {
manager := schema.GetManager()
config := util.GetConfig()
enabled := config.GetParam("snmp", nil)
if enabled == nil {
return
}
host := config.GetString("snmp/address", "localhost:162")
path := "snmp://"
env := newEnvironment(server.db, server.keystoneIdentity, server.timelimit)
err := env.LoadExtensionsForPath(manager.Extensions, path)
if err != nil {
log.Fatal(fmt.Sprintf("Extensions parsing error: %v", err))
}
addr, err := net.ResolveUDPAddr("udp", host)
if err != nil {
log.Fatal(err)
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
log.Fatal(err)
}
buf := make([]byte, 1024)
go func() {
defer conn.Close()
for server.running {
rlen, remote, err := conn.ReadFromUDP(buf)
if err != nil {
log.Error(fmt.Sprintf("[SNMP] failed read bytes %s", err))
return
}
decoded, err := wapsnmp.DecodeSequence(buf[:rlen])
if err != nil {
log.Error(fmt.Sprintf("[SNMP] failed decode bytes %s", err))
continue
}
infos := decoded[3].([]interface{})[4].([]interface{})[1:]
trap := map[string]string{}
for _, info := range infos {
listInfo := info.([]interface{})
oid := listInfo[1].(wapsnmp.Oid)
trap[oid.String()] = fmt.Sprintf("%v", listInfo[2])
}
context := map[string]interface{}{
"trap": trap,
"remote": remote,
}
if err := env.HandleEvent("notification", context); err != nil {
log.Warning(fmt.Sprintf("extension error: %s", err))
}
}
}()
}
示例6: connectDB
func (server *Server) connectDB() error {
config := util.GetConfig()
dbType, dbConnection, _, _ := server.getDatabaseConfig()
maxConn := config.GetInt("database/max_open_conn", db.DefaultMaxOpenConn)
dbConn, err := db.ConnectDB(dbType, dbConnection, maxConn)
if server.sync == nil {
server.db = dbConn
} else {
server.db = &DbSyncWrapper{dbConn}
}
return err
}
示例7: startCRONProcess
//CRON Process
func startCRONProcess(server *Server) {
manager := schema.GetManager()
config := util.GetConfig()
jobList := config.GetParam("cron", nil)
if jobList == nil {
return
}
log.Info("Started CRON process")
c := cron.New()
for _, rawJob := range jobList.([]interface{}) {
job := rawJob.(map[string]interface{})
path := job["path"].(string)
timing := job["timing"].(string)
env := newEnvironment(server.db, server.keystoneIdentity)
err := env.LoadExtensionsForPath(manager.Extensions, path)
if err != nil {
log.Fatal(fmt.Sprintf("Extensions parsing error: %v", err))
}
log.Info("New job for %s / %s", path, timing)
c.AddFunc(timing, func() {
lockKey := lockPath + "/" + path
err := server.sync.Lock(lockKey, false)
if err != nil {
return
}
defer func() {
server.sync.Unlock(lockKey)
}()
tx, err := server.db.Begin()
defer tx.Close()
context := map[string]interface{}{
"path": path,
}
if err != nil {
log.Warning(fmt.Sprintf("extension error: %s", err))
return
}
if err := env.HandleEvent("notification", context); err != nil {
log.Warning(fmt.Sprintf("extension error: %s", err))
return
}
err = tx.Commit()
if err != nil {
log.Warning(fmt.Sprintf("extension error: %s", err))
return
}
return
})
}
c.Start()
}
示例8: getDatabaseConfig
func (server *Server) getDatabaseConfig() (string, string, bool, bool) {
config := util.GetConfig()
databaseType := config.GetString("database/type", "sqlite3")
if databaseType == "json" || databaseType == "yaml" {
log.Fatal("json or yaml isn't supported as main db backend")
}
databaseConnection := config.GetString("database/connection", "")
if databaseConnection == "" {
log.Fatal("no database connection specified in the configuraion file.")
}
databaseDropOnCreate := config.GetBool("database/drop_on_create", false)
databaseCascade := config.GetBool("database/cascade_delete", false)
return databaseType, databaseConnection, databaseDropOnCreate, databaseCascade
}
示例9: mapRoutes
func (server *Server) mapRoutes() {
config := util.GetConfig()
schemaManager := schema.GetManager()
MapNamespacesRoutes(server.martini)
MapRouteBySchemas(server, server.db)
tx, err := server.db.Begin()
if err != nil {
log.Fatal(err)
}
defer tx.Close()
coreSchema, _ := schemaManager.Schema("schema")
if coreSchema == nil {
log.Fatal("Gohan core schema not found")
return
}
policySchema, _ := schemaManager.Schema("policy")
policyList, _, err := tx.List(policySchema, nil, nil)
if err != nil {
log.Info(err.Error())
}
schemaManager.LoadPolicies(policyList)
extensionSchema, _ := schemaManager.Schema("extension")
extensionList, _, err := tx.List(extensionSchema, nil, nil)
if err != nil {
log.Info(err.Error())
}
schemaManager.LoadExtensions(extensionList)
namespaceSchema, _ := schemaManager.Schema("namespace")
if namespaceSchema == nil {
log.Error("No gohan schema. Disabling schema editing mode")
return
}
namespaceList, _, err := tx.List(namespaceSchema, nil, nil)
if err != nil {
log.Info(err.Error())
}
err = tx.Commit()
if err != nil {
log.Info(err.Error())
}
schemaManager.LoadNamespaces(namespaceList)
if config.GetBool("keystone/fake", false) {
middleware.FakeKeystone(server.martini)
}
}
示例10: startCRONProcess
//CRON Process
func startCRONProcess(server *Server) {
config := util.GetConfig()
jobList := config.GetParam("cron", nil)
if jobList == nil {
return
}
if server.sync == nil {
log.Fatalf(fmt.Sprintf("Could not start CRON process because of sync backend misconfiguration."))
util.LogFatalPanic(log)
}
log.Info("Started CRON process")
c := cron.New()
for _, rawJob := range jobList.([]interface{}) {
job := rawJob.(map[string]interface{})
path := job["path"].(string)
timing := job["timing"].(string)
name := strings.TrimPrefix(path, "cron://")
env, err := server.NewEnvironmentForPath(name, path)
if err != nil {
log.Fatal(err.Error())
}
log.Info("New job for %s / %s", path, timing)
c.AddFunc(timing, func() {
lockKey := lockPath + "/" + path
err := server.sync.Lock(lockKey, false)
if err != nil {
return
}
defer func() {
server.sync.Unlock(lockKey)
}()
context := map[string]interface{}{
"path": path,
}
if err != nil {
log.Warning(fmt.Sprintf("extension error: %s", err))
return
}
if err := env.HandleEvent("notification", context); err != nil {
log.Warning(fmt.Sprintf("extension error: %s", err))
return
}
return
})
}
c.Start()
}
示例11: doTemplate
func doTemplate(c *cli.Context) {
template := c.String("template")
manager := schema.GetManager()
configFile := c.String("config-file")
config := util.GetConfig()
err := config.ReadConfig(configFile)
if err != nil {
util.ExitFatal(err)
return
}
templateCode, err := util.GetContent(template)
if err != nil {
util.ExitFatal(err)
return
}
pwd, _ := os.Getwd()
os.Chdir(path.Dir(configFile))
schemaFiles := config.GetStringList("schemas", nil)
if schemaFiles == nil {
util.ExitFatal("No schema specified in configuraion")
} else {
err = manager.LoadSchemasFromFiles(schemaFiles...)
if err != nil {
util.ExitFatal(err)
return
}
}
schemas := manager.OrderedSchemas()
if err != nil {
util.ExitFatal(err)
return
}
tpl, err := pongo2.FromString(string(templateCode))
if err != nil {
util.ExitFatal(err)
return
}
output, err := tpl.Execute(pongo2.Context{"schemas": schemas})
if err != nil {
util.ExitFatal(err)
return
}
os.Chdir(pwd)
fmt.Println(output)
}
示例12: loadNPMModules
func loadNPMModules() {
config := util.GetConfig()
npmPath := config.GetString("extension/npm_path", ".")
files, _ := ioutil.ReadDir(npmPath + "/node_modules/")
for _, f := range files {
if f.IsDir() && !strings.HasPrefix(f.Name(), ".") {
module, err := motto.FindFileModule(f.Name(), npmPath, nil)
if err != nil {
log.Error("Finding module failed %s in %s", err, f.Name())
break
}
if !strings.HasSuffix(module, ".js") {
module = module + "/index.js"
}
loader := motto.CreateLoaderFromFile(module)
motto.AddModule(f.Name(), loader)
}
}
}
示例13: loadConfig
func loadConfig(configFile string) {
if configFile == "" {
return
}
config := util.GetConfig()
err := config.ReadConfig(configFile)
if err != nil {
if configFile != defaultConfigFile {
fmt.Println(err)
os.Exit(1)
}
return
}
err = l.SetUpLogging(config)
if err != nil {
fmt.Printf("Logging setup error: %s\n", err)
os.Exit(1)
return
}
log.Info("logging initialized")
}
示例14: TestOttoExtension
}
}
return nil
}
func TestOttoExtension(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Otto Extension Suite")
}
var _ = Describe("Suite set up and tear down", func() {
var _ = BeforeSuite(func() {
var err error
Expect(os.Chdir(configDir)).To(Succeed())
testDB, err = db.ConnectDB(dbType, dbFile, db.DefaultMaxOpenConn)
Expect(err).ToNot(HaveOccurred(), "Failed to connect database.")
manager := schema.GetManager()
config := util.GetConfig()
Expect(config.ReadConfig(configFile)).To(Succeed())
schemaFiles := config.GetStringList("schemas", nil)
Expect(schemaFiles).NotTo(BeNil())
Expect(manager.LoadSchemasFromFiles(schemaFiles...)).To(Succeed())
Expect(db.InitDBWithSchemas(dbType, dbFile, false, false)).To(Succeed())
})
var _ = AfterSuite(func() {
schema.ClearManager()
os.Remove(dbFile)
})
})
示例15: setupEditor
func setupEditor(server *Server) {
manager := schema.GetManager()
config := util.GetConfig()
editableSchemaFile := config.GetString("editable_schema", "")
golang.RegisterGoCallback("handle_schema",
func(event string, context map[string]interface{}) error {
auth := context["auth"].(schema.Authorization)
if event == "pre_list" {
list := []interface{}{}
total := 0
for _, currentSchema := range manager.OrderedSchemas() {
trimmedSchema, err := GetSchema(currentSchema, auth)
if err != nil {
return err
}
if trimmedSchema != nil {
s := trimmedSchema.Data()
s["url"] = currentSchema.URL
list = append(list, s)
total = total + 1
}
}
context["total"] = total
context["response"] = map[string]interface{}{
"schemas": list,
}
return nil
} else if event == "pre_show" {
ID := context["id"].(string)
currentSchema, _ := manager.Schema(ID)
object, _ := GetSchema(currentSchema, auth)
s := object.Data()
s["url"] = currentSchema.URL
context["response"] = map[string]interface{}{
"schema": s,
}
return nil
}
if event != "pre_create" && event != "pre_update" && event != "pre_delete" {
return nil
}
if editableSchemaFile == "" {
return nil
}
ID := context["id"].(string)
schemasInFile, err := util.LoadMap(editableSchemaFile)
if err != nil {
return nil
}
schemas := schemasInFile["schemas"].([]interface{})
updatedSchemas := []interface{}{}
var existingSchema map[string]interface{}
for _, rawSchema := range schemas {
s := rawSchema.(map[string]interface{})
if s["id"] == ID {
existingSchema = s
} else {
updatedSchemas = append(updatedSchemas, s)
}
}
if event == "pre_create" {
if existingSchema != nil {
return fmt.Errorf("ID has been taken")
}
newSchema := context["resource"].(map[string]interface{})
_, err := schema.NewSchemaFromObj(newSchema)
if err != nil {
return err
}
schemasInFile["schemas"] = append(updatedSchemas, context["resource"].(map[string]interface{}))
context["response"] = map[string]interface{}{
"schema": context["resource"],
}
context["exception"] = map[string]interface{}{
"name": "CustomException",
"message": context["response"],
"code": 201,
}
} else if event == "pre_update" {
if existingSchema == nil {
return fmt.Errorf("Not found or Update isn't supported for this schema")
}
for key, value := range context["resource"].(map[string]interface{}) {
existingSchema[key] = value
}
_, err := schema.NewSchemaFromObj(existingSchema)
if err != nil {
return err
}
schemasInFile["schemas"] = append(updatedSchemas, existingSchema)
context["response"] = map[string]interface{}{
"schema": context["resource"],
}
context["exception"] = map[string]interface{}{
"name": "CustomException",
"message": context["response"],
//.........这里部分代码省略.........