Мне нужно получить значение свойства:
- telegram_token: "telegramtoken"
- other_token: "othertoken"
Но если я наберу Init()
из import api
и инициализирую функцию в 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:}}