找了好久没有找到合适的轮子,自己写了一个
package apolloClient
import (
"bytes"
"encoding/json"
"errors"
"fmt"
g "github.com/phachon/go-logger"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
type Apollo struct {
Burl string //访问地址
AppId string // 应用id
NameSpace string //命名空间
Env string //环境信息
Cluster string //集群名称
Cookies []*http.Cookie
C *http.Client
}
var logger *g.Logger
func init(){
logger = g.NewLogger()
logger.Detach("console")
// console adapter config
consoleConfig := &g.ConsoleConfig{
Color: true, // Does the text display the color
JsonFormat: false, // Whether or not formatted into a JSON string
Format: "", // JsonFormat is false, logger message output to console format string
}
// add output to the console
logger.Attach("console", g.LOGGER_LEVEL_INFO, consoleConfig)
}
//登陆apollo,并获取cookie
func InitApollo(name,password,baseUrl string,apollo *Apollo) {
apollo.C = &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
payload := make(url.Values)
payload.Add("username", name)
payload.Add("password", password)
payload.Add("login-submit", "登录")
loginUrl := fmt.Sprintf("%s/signin", baseUrl)
req, _ := http.NewRequest(http.MethodPost, loginUrl, strings.NewReader(payload.Encode()))
//设置header
req.Header["Content-Type"] = []string{
"application/x-www-form-urlencoded"}
req.Header["Upgrade-Insecure-Requests"] = []string{
"1"}
req.Header["User-Agent"] = []string{
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0"}
req.AddCookie(&http.Cookie{
Name: "NG_TRANSLATE_LANG_KEY", Value: "zh-CN"})
resp, err := apollo.C.Do(req)
if err != nil {
panic(err)
}
defer func() {
_ = resp.Body.Close() }()
if resp.StatusCode == 200{
logger.Info("登录apollo环境成功!")
}
apollo.Cookies = resp.Cookies()
apollo.Burl=baseUrl
//return apollo
}
//请求头设置
func (a *Apollo) reqHeaderSetup(req *http.Request) {
for _, cookie := range a.Cookies {
req.AddCookie(cookie)
}
referUrl:=fmt.Sprintf("%s/config.html",a.Burl)
req.AddCookie(&http.Cookie{
Name: "NG_TRANSLATE_LANG_KEY", Value: "zh-CN"})
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0")
req.Header.Set("Referer", referUrl)
}
//获取指定应用的命名空间下的配置的信息
func (a *Apollo) GetConfInfo() ([]map[string]interface{
}, error) {
var (
err error
resp *http.Response
req *http.Request
resultSlice []map[string]interface{
}
)
apiUrl := fmt.Sprintf("/apps/%s/envs/%s/clusters/%s/namespaces/%s", a.AppId, a.Env, a.Cluster, a.NameSpace)
//fmt.Println(apiUrl)
req, err = http.NewRequest(http.MethodGet, a.Burl+apiUrl, nil)
if err != nil {
return nil, err
}
//设置请求头
a.reqHeaderSetup(req)
resp, err = a.C.Do(req)
if err != nil {
return nil, err
}
defer func() {
_ = resp.Body.Close() }()
//result:=make