golang使用宝塔API快速建站

golang使用宝塔API快速建站

Anderyly
2022-06-10 / 0 评论 / 13 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2024年02月27日,已超过221天没有更新,若内容或图片失效,请留言反馈。

由于某些原因,需要用一行命令来创建宝塔以及数据库,此函数基于官方的API

注意:宝塔创建网站需要使用php 以下代码使用php80

下面代码用到了第三方库github.com/spf13/viper

md5的计算就不贴了很简单

BtServer主文件

/*
 * @Author anderyly
 * @email admin@aaayun.cc
 * @link http://blog.aaayun.cc/
 * @copyright Copyright (c) 2022
 */

package ay

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "runtime"
    "strconv"
    "strings"
    "time"
)

type BtServer struct {
}

// GetSign 获取签名
func (con BtServer) GetSign() map[string]string {
    res := make(map[string]string, 2)
    res["request_time"] = strconv.FormatInt(time.Now().Unix(), 10)
    res["request_token"] = MD5(res["request_time"] + MD5(Yaml.GetString("bt.code")))

    return res
}

// GetSiteId 获取网站id
func (con BtServer) GetSiteId() {

    type r struct {
        Where string `json:"where"`
        Page  string `json:"page"`
        Data  []struct {
            Id          int    `json:"id"`
            Name        string `json:"name"`
            Path        string `json:"path"`
            Status      string `json:"status"`
            Ps          string `json:"ps"`
            Addtime     string `json:"addtime"`
            Edate       string `json:"edate"`
            Type        string `json:"type"`
            TypeVersion string `json:"type_version"`
            BackupCount int    `json:"backup_count"`
            Domain      int    `json:"domain"`
            Ssl         int    `json:"ssl"`
        } `json:"data"`
    }

    url := Yaml.GetString("bt.panel") + "/data?action=getData&table=sites"

    data := con.GetSign()

    data["limit"] = "1"
    data["search"] = Yaml.GetString("bt.site")

    res := con.Http(url, data)

    var rj r
    json.Unmarshal([]byte(res), &rj)

    siteId := 0

    if len(rj.Data) == 1 {
        for _, v := range rj.Data {
            siteId = v.Id
        }
    }

    Yaml.Set("bt.site_id", siteId)

    Yaml.WriteConfig()
}

func (con BtServer) Http(url string, data map[string]string) string {
    str := ""
    for k, v := range data {
        str += k + "=" + v + "&"
    }
    resp, err := http.Post(url,
        "application/x-www-form-urlencoded",
        strings.NewReader(strings.TrimRight(str, "&")))
    if err != nil {
        fmt.Println(err)
    }

    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }

    return string(body)
}

// Create 创建网站
func (con BtServer) Create() (bool, string) {

    type r struct {
        SiteStatus     bool   `json:"siteStatus"`
        SiteId         int    `json:"siteId"`
        FtpStatus      bool   `json:"ftpStatus"`
        DatabaseStatus bool   `json:"databaseStatus"`
        Status         bool   `json:"status"`
        Msg            string `json:"msg"`
    }

    url := Yaml.GetString("bt.panel") + "/site?action=AddSite"

    data := con.GetSign()

    pass := MD5(strconv.FormatInt(time.Time{}.Unix(), 10))[:10]

    Yaml.Set("mysql.user", "shop")
    Yaml.Set("mysql.database", "shop")
    Yaml.Set("mysql.password", pass)
    Yaml.Set("mysql.localhost", "127.0.0.1")
    Yaml.Set("mysql.port", "3306")

    if runtime.GOOS == "linux" {
        data["path"] = "/www/wwwroot/shop"
    } else {
        data["path"] = "D:/wwwroot/shop"
    }

    data["webname"] = `{"domain":"` + Yaml.GetString("bt.site") + `","domainlist":[],"count":0}`
    data["type_id"] = "0"
    data["type"] = "PHP"
    data["version"] = "80"
    data["port"] = "80"
    data["ps"] = "微营销"
    data["ftp"] = "false"
    data["sql"] = "true"
    data["codeing"] = "utf8mb4"
    data["datauser"] = "shop"
    data["datapassword"] = pass

    res := con.Http(url, data)

    var rj r
    json.Unmarshal([]byte(res), &rj)

    Yaml.Set("bt.site_id", rj.SiteId)

    if rj.SiteStatus && rj.DatabaseStatus {
        Yaml.WriteConfig()
        return true, "success"
    } else {
        return false, rj.Msg
    }

}

// GetDomain 获取域名
func (con BtServer) GetDomain() []map[string]string {

    type r struct {
        Id      int    `json:"id"`
        Pid     int    `json:"pid"`
        Name    string `json:"name"`
        Port    int    `json:"port"`
        Addtime string `json:"addtime"`
    }

    url := Yaml.GetString("bt.panel") + "/data?action=getData&table=domain"

    data := con.GetSign()

    data["search"] = Yaml.GetString("bt.site_id")
    data["list"] = "true"

    res := con.Http(url, data)

    var rj []r
    json.Unmarshal([]byte(res), &rj)

    var s []map[string]string
    for _, v := range rj {
        s = append(s, map[string]string{
            "id":   strconv.Itoa(v.Id),
            "name": v.Name,
            "port": strconv.Itoa(v.Port),
        })
    }

    return s

}

// DelDomain 删除域名
func (con BtServer) DelDomain(domain, port string) (bool, string) {

    type r struct {
        Status bool   `json:"status"`
        Msg    string `json:"msg"`
    }

    url := Yaml.GetString("bt.panel") + "/site?action=DelDomain"

    data := con.GetSign()

    data["id"] = Yaml.GetString("bt.site_id")
    data["webname"] = Yaml.GetString("bt.site")
    data["domain"] = domain
    data["port"] = port

    res := con.Http(url, data)

    var rj r
    json.Unmarshal([]byte(res), &rj)

    return rj.Status, rj.Msg
}

// SetDomain 设置域名
func (con BtServer) SetDomain(domain string) (bool, string) {

    type r struct {
        Status bool   `json:"status"`
        Msg    string `json:"msg"`
    }

    url := Yaml.GetString("bt.panel") + "/site?action=AddDomain"

    data := con.GetSign()

    data["id"] = Yaml.GetString("bt.site_id")
    data["webname"] = Yaml.GetString("bt.site")
    data["domain"] = domain

    res := con.Http(url, data)

    var rj r
    json.Unmarshal([]byte(res), &rj)

    return rj.Status, rj.Msg
}

// UpdateDomain 更新网站域名
func (con BtServer) UpdateDomain(str string) (bool, string) {
    domainArr := strings.Split(str, "=")
    btDomain := con.GetDomain()
    for _, v := range domainArr {

        domainS := 0

        for _, v1 := range btDomain {
            if v == v1["name"] {
                domainS = 1
                break
            }
        }
        if domainS != 1 {
            con.SetDomain(v)
        }
    }
    return true, "success"
}

yaml文件

bt:
  code: QGg5Ct3BlSKlvZmvVk537vuVToJ8j8ci
  panel: http://127.0.0.1:8888
  site: baidu1.com
  site_id: 1
domain: http://127.0.0.1:8082
mysql:
  database: shop
  localhost: 127.0.0.1
  password: root
  port: 3306
  user: root
0

评论 (0)

取消