add config and tmdb

This commit is contained in:
Simon Ding
2024-06-19 15:28:03 +08:00
parent 423b9258c9
commit cd7440dde0
5 changed files with 152 additions and 0 deletions

42
cfg/config.go Normal file
View File

@@ -0,0 +1,42 @@
package cfg
import (
"polaris/log"
"github.com/pkg/errors"
"github.com/spf13/viper"
)
type Config struct {
TMDB TMDB `mapstructure:"tmdb"`
}
type TMDB struct {
ApiKey string `mapstructure:"apiKey"`
}
func LoadConfig() (*Config, error) {
viper.SetConfigName("config") // name of config file (without extension)
viper.SetConfigType("yml") // REQUIRED if the config file does not have the extension in the name
viper.AddConfigPath(".")
viper.AddConfigPath("/app/data")
var cc Config
// optionally look for config in the working directory
err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
log.Info("create config file")
viper.SafeWriteConfig()
} else {
// Config file was found but another error was produced
}
return nil, errors.Wrap(err, "load config")
}
if err := viper.Unmarshal(&cc); err != nil {
return nil, errors.Wrap(err, "unmarshal file")
}
return &cc, err
}

42
cfg/pkg/tmdb/tmdb.go Normal file
View File

@@ -0,0 +1,42 @@
package tmdb
import (
"polaris/log"
tmdb "github.com/cyruzin/golang-tmdb"
"github.com/pkg/errors"
)
type Client struct {
apiKey string
tmdbClient *tmdb.Client
}
func NewClient(apiKey string) (*Client, error) {
tmdbClient, err := tmdb.Init(apiKey)
if err != nil {
return nil, errors.Wrap(err, "new tmdb client")
}
return &Client{
apiKey: apiKey,
tmdbClient: tmdbClient,
}, nil
}
func (c *Client) GetTvDetails(id int, language string) {
language = wrapLanguage(language)
d, err := c.tmdbClient.GetTVDetails(id, map[string]string{
"language": language,
})
log.Infof("error %v", err)
log.Infof("detail %+v", d)
}
func wrapLanguage(lang string) string {
if lang == "" {
lang = "zh-CN"
}
return lang
}