首页 > 解决方案 > How to get value property in console if use import func?

问题描述

I need to get property value:

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:}}

标签: goyaml

解决方案


Modify the YAML to match the expected structure by indenting the token fields:

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

推荐阅读