go - How to get value property in console if use import func?
问题描述
I need to get property value:
- telegram_token: "telegramtoken"
- other_token: "othertoken"
But if I do Init()
of import api
and initialize function in func main()
I don't get property value.
Why?
Thanks!
This is works:
package main
import (
"fmt"
"github.com/go-yaml/yaml"
)
var (
cfg Config
configData = []byte(`api:
telegram_token: "telegramtoken"
other_token: "othertoken"`)
)
type Config struct {
API ConfigAPI `yaml:"api"`
}
type ConfigAPI struct {
TelegramToken string `yaml:"telegram_token"`
OtherToken string `yaml:"other_token"`
}
func (c *Config) parse() {
err := yaml.Unmarshal(configData, c)
if err != nil {
fmt.Println(err.Error())
}
}
func Init() {
cfg.parse()
fmt.Printf("%+v\n", cfg)
}
func main() {
Init()
}
Console:
{API:{TelegramToken:telegramtoken OtherToken:othertoken}}
Doesn't work:
package api
import (
"fmt"
"github.com/go-yaml/yaml"
)
var (
cfg Config
configData = []byte(`api:
telegram_token: "telegramtoken"
waves_token: "wavestoken"`)
)
type Config struct {
API ConfigAPI `yaml:"api"`
}
type ConfigAPI struct {
TelegramToken string `yaml:"telegram_token"`
WavesToken string `yaml:"waves_token"`
}
func (c *Config) parse() {
err := yaml.Unmarshal(configData, c)
if err != nil {
fmt.Println(err.Error())
}
}
func Init() {
cfg.parse()
fmt.Printf("%+v\n", cfg)
}
package main
, see on api.Init()
// The daemon that starts the API in background process.
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/julienschmidt/httprouter"
api "github.com/krypton-code/waves-bot/pkg/api"
)
var (
host = "https://api.telegram.org/bot"
method = "/getMe"
)
// Index - home page.
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprint(w, "<h1>Server of TelegaBot for Waves Platform is running!</h1>\n")
}
func main() {
api.Init()
router := httprouter.New()
router.GET("/", Index)
s := &http.Server{
Addr: ":8089",
Handler: router,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Printf("\nApp listening on port%s. Go to http://localhost:8089/", s.Addr)
log.Fatal(s.ListenAndServe())
}
Console:
{API:{TelegramToken: WavesToken:}}
解决方案
Modify the YAML to match the expected structure by indenting the token fields:
configData = []byte(`api:
telegram_token: "telegramtoken"
waves_token: "wavestoken"`)
)
推荐阅读
- jmeter - 如何在beanshell处理器之间传递filewriter对象
- c# - 从设备管理器中读取属性?
- asp.net-mvc - 使用 _LoginPartial 和 .NET MVC 的动态导航栏
- python - Python Pandas - 非连续时间序列?
- jquery - autocomplete() 生成非文本输出
- flutter - 是否有标准/通常的数据存储位置?
- angular - 在 Angular 的选项卡式模式中正确路由
- c# - 如何编写递归函数
- android - 为 Fused Location 提供程序 onLocationChanged 设置计时器
- python-3.x - 如何获得离集群中心最近的N个数据点?