在revel.Controller中,如何获取在app.conf中设置的端口?

huangapple go评论82阅读模式
英文:

In revel.Controller, How to get port set in app.conf

问题

使用revel框架(golang),我如何获取在app.conf中设置的端口号?

// 在app.conf中
http.port=9090

我必须在控制器中使用我的服务器端口号(例如OAuth编码),例如

requestToken,url,err:= TWITTER.GetRequestTokenAndUrl(
"http://127.0.0.1:9090/Application/Authenticate",
)

我不想通过硬编码来写端口号。
使用revel,有没有一种好的方法来获取在app.conf中设置的端口号(或任何其他配置值)?

提前谢谢。

英文:

Using revel framework (golang), how can I get port I set in app.conf?

// in app.conf
http.port=9090

And I have to use my server's port number in controllers (for example OAuth coding) such as

requestToken, url, err := TWITTER.GetRequestTokenAndUrl(
    "http://127.0.0.1:9090/Application/Authenticate",
)

I don't want to write port number by hard coding.
Using revel, is there any good way to get port number (or any other conf values) set in app.conf?

Thank you in advance

答案1

得分: 2

也许这份文档会有用 - http://robfig.github.io/revel/docs/godoc/config.html

例如:

// 加载 app.conf
var err error
Config, err = LoadConfig("app.conf")
if err != nil || Config == nil {
    log.Fatalln("加载 app.conf 失败:", err)
}
HttpPort = Config.IntDefault("http.port", 9000)

另一种方法可以替代直接加载(参见 modules/db/app/db.go

import (
    "github.com/robfig/revel"
)

if option, found = revel.Config.String("option"); !found {
    revel.ERROR.Fatal("未找到选项.")
}
英文:

May be this documentation will be useful - http://robfig.github.io/revel/docs/godoc/config.html

For example

// Load app.conf
var err error
Config, err = LoadConfig("app.conf")
if err != nil || Config == nil {
    log.Fatalln("Failed to load app.conf:", err)
}
HttpPort = Config.IntDefault("http.port", 9000)

An another approach may be used instead direct loading (see modules/db/app/db.go)

import (
	"github.com/robfig/revel"
)

if option, found = revel.Config.String("option"); !found {
	revel.ERROR.Fatal("No option found.")
}

答案2

得分: 0

更新的答案

在你的文件app/init.go中,你必须在一个自定义函数中获取配置值。

这个自定义函数必须在func init()中注册,并使用revel.OnAppStart(MyFunc)


如果你尝试直接从init()函数中获取配置值,你会收到一个类似下面的错误:

panic: runtime error: invalid memory address or nil pointer dereference
英文:

Updated Answer

In your file app/init.go you must retrieve config values within a custom-made function.

This custom made function must be registered in func init() with revel.OnAppStart(MyFunc).


If you attempt to retrieve config values directly from the init() func, you will recieve an error that looks something like this:

panic: runtime error: invalid memory address or nil pointer dereference

huangapple
  • 本文由 发表于 2014年1月26日 15:36:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/21360956.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定