首页 > 其他分享 >go写入配置文件

go写入配置文件

时间:2024-04-10 21:35:39浏览次数:26  
标签:配置文件 err nil 写入 home go path config string

package install

import (
"fmt"
"io/ioutil"
"os"

v2 "gopkg.in/yaml.v2"

"github.com/fanux/sealos/net"
"github.com/fanux/sealos/pkg/logger"
)

const (
defaultConfigPath = "/.sealos"
defaultConfigFile = "/config.yaml"
defaultAPIServerDomain = "apiserver.cluster.local"
)

// SealConfig for ~/.sealos/config.yaml
type SealConfig struct {
Masters []string
Nodes []string
//config from kubeadm.cfg. ex. cluster.local
DNSDomain string
APIServerCertSANs []string

//SSHConfig
User string
Passwd string
PrivateKey string
PkPassword string
//ApiServer ex. apiserver.cluster.local
APIServerDomain string
Network string
VIP string
PkgURL string
Version string
Repo string
PodCIDR string
SvcCIDR string
//certs location
CertPath string
CertEtcdPath string
//lvscare images
LvscareName string
LvscareTag string
AliOss
}

// Dump is
func (c *SealConfig) Dump(path string) {
home, _ := os.UserHomeDir()
if path == "" {
path = home + defaultConfigPath + defaultConfigFile
}
MasterIPs = ParseIPs(MasterIPs)
c.Masters = MasterIPs
NodeIPs = ParseIPs(NodeIPs)
c.Nodes = ParseIPs(NodeIPs)
c.User = SSHConfig.User
c.Passwd = SSHConfig.Password
c.PrivateKey = SSHConfig.PkFile
c.PkPassword = SSHConfig.PkPassword
c.APIServerDomain = APIServer
c.Network = Network
c.VIP = VIP
c.PkgURL = PkgURL
c.Version = Version
c.Repo = Repo
c.SvcCIDR = SvcCIDR
c.PodCIDR = PodCIDR

c.DNSDomain = DNSDomain
c.APIServerCertSANs = APIServerCertSANs
c.CertPath = CertPath
c.CertEtcdPath = CertEtcdPath
//lvscare
c.LvscareName = LvscareImage.Image
c.LvscareTag = LvscareImage.Tag
// oss
c.AliOss.AccessKeyID = AccessKeyID
c.AliOss.AccessKeySecrets = AccessKeySecrets
c.AliOss.OssEndpoint = OssEndpoint
c.AliOss.BucketName = BucketName
c.AliOss.ObjectPath = ObjectPath
y, err := v2.Marshal(c)
if err != nil {
logger.Error("dump config file failed: %s", err)
}

err = os.MkdirAll(home+defaultConfigPath, os.ModePerm)
if err != nil {
logger.Warn("create default sealos config dir failed, please create it by your self mkdir -p /root/.sealos && touch /root/.sealos/config.yaml")
}

if err = ioutil.WriteFile(path, y, 0644); err != nil {
logger.Warn("write to file %s failed: %s", path, err)
}
}

func Dump(path string, content interface{}) error {
y, err := v2.Marshal(content)
if err != nil {
logger.Error("dump config file failed: %s", err)
return err
}
home, _ := os.UserHomeDir()
err = os.MkdirAll(home+defaultConfigPath, os.ModePerm)
if err != nil {
logger.Error("create dump dir failed %s", err)
return err
}

_ = ioutil.WriteFile(path, y, 0644)
return nil
}

// Load is
func (c *SealConfig) Load(path string) (err error) {
if path == "" {
home, _ := os.UserHomeDir()
path = home + defaultConfigPath + defaultConfigFile
}
y, err := ioutil.ReadFile(path)
if err != nil {
return fmt.Errorf("read config file %s failed %w", path, err)
}

err = v2.Unmarshal(y, c)
if err != nil {
return fmt.Errorf("unmarshal config file failed: %w", err)
}

MasterIPs = c.Masters
NodeIPs = c.Nodes
SSHConfig.User = c.User
SSHConfig.Password = c.Passwd
SSHConfig.PkFile = c.PrivateKey
SSHConfig.PkPassword = c.PkPassword
APIServer = c.APIServerDomain
Network = c.Network
VIP = c.VIP
PkgURL = c.PkgURL
Version = c.Version
Repo = c.Repo
PodCIDR = c.PodCIDR
SvcCIDR = c.SvcCIDR
DNSDomain = c.DNSDomain
APIServerCertSANs = c.APIServerCertSANs
CertPath = c.CertPath
CertEtcdPath = c.CertEtcdPath
//lvscare
LvscareImage.Image = c.LvscareName
LvscareImage.Tag = c.LvscareTag

// 优先使用使用命令行, 再使用配置文件
if AccessKeyID == "" || AccessKeySecrets == "" ||
OssEndpoint == "" || BucketName == "" || ObjectPath == "" {
AccessKeyID = c.AliOss.AccessKeyID
AccessKeySecrets = c.AliOss.AccessKeySecrets
OssEndpoint = c.AliOss.OssEndpoint
BucketName = c.AliOss.BucketName
ObjectPath = c.AliOss.ObjectPath
}
return
}

func Load(path string, content interface{}) error {
y, err := ioutil.ReadFile(path)
if err != nil {
logger.Error("read config file %s failed %s", path, err)
os.Exit(0)
}

err = v2.Unmarshal(y, content)
if err != nil {
logger.Error("unmarshal config file failed: %s", err)
}
return nil
}

func (c *SealConfig) ShowDefaultConfig() {
home, _ := os.UserHomeDir()
c.Masters = []string{"192.168.0.2", "192.168.0.2", "192.168.0.2"}
c.Nodes = []string{"192.168.0.3", "192.168.0.4"}
c.User = "root"
c.Passwd = "123456"
c.PrivateKey = home + "/.ssh/id_rsa"
c.APIServerDomain = defaultAPIServerDomain
c.Network = net.CALICO
c.VIP = "10.103.97.2"
c.PkgURL = home + "/kube1.17.13.tar.gz"
c.Version = "v1.17.13"
c.Repo = "k8s.gcr.io"
c.PodCIDR = "100.64.0.0/10"
c.SvcCIDR = "10.96.0.0/12"
c.APIServerCertSANs = []string{"apiserver.cluster.local", "127.0.0.1"}
c.CertPath = home + "/.sealos/pki"
c.CertEtcdPath = home + "/.sealos/pki/etcd"
c.LvscareName = "fanux/lvscare"
c.LvscareTag = "latest"

y, err := v2.Marshal(c)
if err != nil {
logger.Error("marshal config file failed: %s", err)
}

logger.Info("\n\n%s\n\n", string(y))
logger.Info("Please save above config in ~/.sealos/config.yaml and edit values on your own")
}

标签:配置文件,err,nil,写入,home,go,path,config,string
From: https://www.cnblogs.com/cheyunhua/p/18127510

相关文章

  • goto语句
    今天给大家分享一个小知识----goto语句。goto语句就是可以随意无条件的转移语句,运用形式是:标记名:...        goto标记名;这两个中间可以写任意内容,标记名也可以在goto语句后面,位置随意。给大家分享一个好玩的例子:一个定时关机程序,输入我是小狗,取消关机,输......
  • django simpleui 的list_display添加自定义列、显示图片 及alert弹窗的设置方法
    参考djangosimpleui的list_display添加自定义列、显示图片及alert弹窗的设置方法-CSDN博客环境:python:3.8.xDjango:3.2.xDjango-simpleui:2021.x先定义下模型#models.pyclassDog(models.Model):name=models.CharField(max_length=15,verbose_name='小狗名字')......
  • Java程序中两种配置文件(xml和properties)的加载读取方法
    ​ Java程序中,经常需要从配置文件中加载并读取设置,以支持不同的配置环境和参数。最常用的配置文件格式是XML和properties。两种方法都非常基础,适合于简单的配置文件读取需求。对于更复杂的需求,可能需要更高级的解析技术或第三方库。参考文档:Java程序中两种配置文件(xml和prope......
  • Go 源码之旅-开篇
    欢迎来到《Go源码之旅》专栏!在这个专栏中,我们将深入探索Go编程语言的内部数据结构的工作原理,一起踏上一段令人兴奋的源码之旅。我们将一步步解析关键的数据结构底层工作原理以及一些常用框架的设计原理及其源码。无论你是初学者还是有经验的开发人员,这个专栏都将为你提......
  • 牛蛙!GoFrame2.7正式版的监控组件真是及时雨
    声明:本文首发在同名公众号:王中阳Go,未经授权禁止转载。......
  • 基于Golang的Nano游戏服务器框架
    在游戏开发过程中,一个高效的服务器框架是至关重要的。Nano正是这样一个框架,它以Golang为基础,提供了轻量级、高性能的服务器解决方案。下面,我们将深入探讨Nano的设计理念、核心特性以及如何在实战中使用它。Nano框架概述Nano是一个针对游戏服务器的框架,能够帮助开发者快速......
  • python收到MQTT消息后写入mySQL
    python收MQTT消息和写mySQL的代码在前面的文章都有介绍,这里直接上完整的功能代码mqtt2mysql.py#python3.6importloggingimportrandomimporttimeimportmysql.connector#frompaho.mqttimportclientasmqtt_clientimportpaho.mqtt.clientasmqttBROKER......
  • 2024-04-10:用go语言,考虑一个非负整数数组 A, 如果数组中相邻元素之和为完全平方数,我们
    2024-04-10:用go语言,考虑一个非负整数数组A,如果数组中相邻元素之和为完全平方数,我们称这个数组是正方形数组。现在要计算A的正方形排列的数量。两个排列A1和A2被认为是不同的,如果存在至少一个索引i,满足A1[i]!=A2[i]。输入:[1,17,8]。输出:2。答案2024-04-10:来自左......
  • GPT-4 Turbo 融合视觉能力;Google 新添 AI 视频应用 Vids丨 RTE 开发者日报 Vol.181
      开发者朋友们大家好: 这里是「RTE开发者日报」,每天和大家一起看新闻、聊八卦。我们的社区编辑团队会整理分享RTE(RealTimeEngagement)领域内「有话题的新闻」、「有态度的观点」、「有意思的数据」、「有思考的文章」、「有看点的会议」,但内容仅代表编辑的个人观点......
  • Python 一骑绝尘,Go 进入 TOP 10 | TIOBE 3 月榜单发布
    近日,3月TIOBE编程语言榜单已最新出炉,一起来看看本月有什么值得关注的新变化吧!1、Python可谓“一骑绝尘”与前几个月相比,本月的Python可谓“一骑绝尘”——哪怕与第二名的C语言(11.17%)比较,其市场份额(15.63%)都领先了近4.5%。得益于过去一年AI热潮席卷全球,被许多人......