gpt4 book ai didi

go - 如果使用 import func,如何在控制台中获取 value 属性?

转载 作者:数据小太阳 更新时间:2023-10-29 03:03:08 26 4
gpt4 key购买 nike

我需要获取属性值:

  • telegram_token:“电报 token ”
  • other_token: "othertoken"

但是如果我执行 import apiInit() 并在 func main() 中初始化函数,我不会获得属性值。为什么?谢谢!

这是可行的:

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()
}

控制台:{API:{TelegramToken:telegramtoken OtherToken:othertoken}}

不起作用:

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,见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())
}

控制台:{API:{TelegramToken: WavesToken:}}

最佳答案

通过缩进标记字段来修改 YAML 以匹配预期的结构:

    configData = []byte(`api:
telegram_token: "telegramtoken"
waves_token: "wavestoken"`)
)

关于go - 如果使用 import func,如何在控制台中获取 value 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50391792/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com