This commit is contained in:
xinghuo 2018-07-07 22:53:51 +08:00
parent fe0e28a058
commit cd0e5d4afd
19 changed files with 167 additions and 164 deletions

20
control
View File

@ -7,7 +7,7 @@ export GOPATH=$DIR
export GOBIN=$DIR/bin/
app=$BASENAME
conf=src/conf/app.conf
conf=$DIR/src/conf/app.conf
pidfile=$DIR/$BASENAME.pid
logfile=$DIR/$BASENAME.log
@ -23,8 +23,8 @@ logfile=$DIR/$BASENAME.log
}
function build() {
gofmt -w src/
cd src/
gofmt -w $DIR/src/
cd $DIR/src/
go build -o $BASENAME
if [ $? -ne 0 ]; then
exit $?
@ -48,7 +48,7 @@ function start() {
if ! [ -f $conf ];then
echo "Config file $conf doesn't exist, creating one."
fi
cd src/
cd $DIR/src/
nohup ./$BASENAME >$logfile 2>&1 &
sleep 1
running=`ps -p $! | grep -v "PID TTY" | wc -l`
@ -98,22 +98,22 @@ function status() {
fi
}
function run() {
cd src/
cd $DIR/src/
./$BASENAME -docker
#go run main.go
}
function rundocker() {
cd src/
cd $DIR/src/
./$BASENAME -docker
#go run main.go
}
function init() {
cd src/
cd $DIR/src/
./$BASENAME -syncdb
#go run main.go
}
function beerun() {
cd src/
cd $DIR/src/
bee run
}
@ -121,12 +121,12 @@ function tailf() {
tail -f $logfile
}
function docs() {
cd src/
cd $DIR/src/
bee generate docs
}
function sslkey() {
cd src/conf/ssl
cd $DIR/src/conf/ssl
###CA:
#私钥文件
openssl genrsa -out ca.key 2048

View File

@ -8,6 +8,7 @@ import (
"github.com/dgrijalva/jwt-go"
)
//TODO 另一版的api验证 废弃
//基类
type BaseApiController struct {

View File

@ -75,4 +75,3 @@ func (this *BaseController) SetJson(code int, data interface{}, Msg string) {
}
}

View File

@ -44,7 +44,7 @@ func (c *LoginController) Post() {
user.AuthKey = userAuth
models.UpdateUserById(&user)
}
user.PasswordHash=""
user.PasswordHash = ""
c.SetJson(0, user, "")
return
}

View File

@ -19,7 +19,7 @@ type P2pinfo struct {
Host string
Status string
Pid int
Pname string
Pname string
}
func (c *CheckController) Get() {

View File

@ -54,12 +54,12 @@ func (c *RegisterController) Post() {
err = o.Raw("SELECT * FROM `user` WHERE username= ?", registerUsername).QueryRow(&user)
beego.Info(user)
if err == nil {
userId,_:=c.GetInt("id")
if userId==0{
userId, _ := c.GetInt("id")
if userId == 0 {
c.SetJson(1, nil, "用户已存在,请更换账户名")
return
}
if userId !=user.Id{
if userId != user.Id {
c.SetJson(1, nil, "用户不存在")
return
}
@ -67,7 +67,7 @@ func (c *RegisterController) Post() {
user.Email = registerEmail
user.Realname = registerRealname
if user.Role == 20 {
o.Raw("DELETE FROM `group` WHERE `user_id` = ? ",user.Id).Exec()
o.Raw("DELETE FROM `group` WHERE `user_id` = ? ", user.Id).Exec()
pro_ids := common.GetString(registerData["pro_ids"])
pro_idArr := strings.Split(pro_ids, ",")
for _, pro_id := range pro_idArr {

View File

@ -4,10 +4,10 @@ import (
"controllers"
"encoding/json"
"github.com/astaxie/beego"
"library/common"
"library/components"
"models"
"time"
"library/components"
"library/common"
)
type SaveController struct {
@ -38,14 +38,14 @@ func (c *SaveController) Post() {
if err == nil {
task.Hosts = ss.Hosts
}
if ss.IsGroup==1{
if ss.IsGroup == 1 {
s := components.BaseComponents{}
s.SetProject(ss)
mapHost:=s.GetGroupHost()
mapHost := s.GetGroupHost()
for k, v := range mapHost {
task1:=task
task1.Hosts=v
task1.Title=task1.Title+"第"+common.GetString(k)+"批"
task1 := task
task1.Hosts = v
task1.Title = task1.Title + "第" + common.GetString(k) + "批"
models.AddTask(&task1)
}
c.SetJson(0, task, "修改成功")

View File

@ -9,26 +9,24 @@ type UserController struct {
controllers.BaseController
}
func (c *UserController) Get() {
userId ,_:= c.GetInt("id")
if userId==0{
userId, _ := c.GetInt("id")
if userId == 0 {
o := orm.NewOrm()
var users []orm.Params
o.Raw("SELECT * FROM `user` ").Values(&users)
c.SetJson(0, users, "")
return
}else{
} else {
o := orm.NewOrm()
var users []orm.Params
var res orm.Params
i,err:=o.Raw("SELECT * FROM `user` where id = ? ",userId).Values(&users)
if err == nil && i>0 {
res=users[0]
i, err := o.Raw("SELECT * FROM `user` where id = ? ", userId).Values(&users)
if err == nil && i > 0 {
res = users[0]
}
c.SetJson(0, res, "")
return
}
}

View File

@ -9,7 +9,6 @@ type UserProjectController struct {
controllers.BaseController
}
func (c *UserProjectController) Get() {
userId := c.GetString("user_id")
o := orm.NewOrm()

View File

@ -135,7 +135,7 @@ func (c *ReleaseController) releaseHandling() error {
c.failHandling(&s)
return err
}
} else if c.Project.RepoType == "file" || c.Project.RepoType == "jenkins" {
} else if c.Project.RepoType == "file" || c.Project.RepoType == "jenkins" {
f := components.BaseFile{}
f.SetBaseComponents(s)
err = f.UpdateToVersion()

View File

@ -37,7 +37,7 @@ type ExecResult struct {
StartTime time.Time
EndTime time.Time
Error error
ErrorInfo string
ErrorInfo string
}
// execute the command and return a result structure
@ -54,7 +54,7 @@ func (exec *HostSession) Exec(id int, command string, config ssh.ClientConfig) *
if err != nil {
result.Error = err
result.ErrorInfo=err.Error()
result.ErrorInfo = err.Error()
result.Result = "ssh连接出错请检查key信任或ip是否正确"
return result
}
@ -62,7 +62,7 @@ func (exec *HostSession) Exec(id int, command string, config ssh.ClientConfig) *
session, err := client.NewSession()
if err != nil {
result.ErrorInfo=err.Error()
result.ErrorInfo = err.Error()
result.Result = "ssh连接出错请检查key信任或ip是否正确"
result.Error = err
return result
@ -81,8 +81,8 @@ func (exec *HostSession) Exec(id int, command string, config ssh.ClientConfig) *
start := time.Now()
if err := session.Run(command); err != nil {
result.Error = err
result.ErrorInfo=err.Error()
result.Result = b1.String() +" 错误信息:"+err.Error()
result.ErrorInfo = err.Error()
result.Result = b1.String() + " 错误信息:" + err.Error()
return result
}
end := time.Now()
@ -107,7 +107,7 @@ func (exec *HostSession) Transfer(id int, localFilePath string, remoteFilePath s
client, err := ssh.Dial("tcp", exec.Hostname+":"+strconv.Itoa(exec.Port), &config)
if err != nil {
result.ErrorInfo=err.Error()
result.ErrorInfo = err.Error()
result.Result = "ssh连接出错请检查key信任或ip是否正确"
result.Error = err
return result
@ -116,7 +116,7 @@ func (exec *HostSession) Transfer(id int, localFilePath string, remoteFilePath s
session, err := client.NewSession()
if err != nil {
result.ErrorInfo=err.Error()
result.ErrorInfo = err.Error()
result.Result = "ssh连接出错请检查key信任或ip是否正确"
result.Error = err
return result
@ -136,7 +136,7 @@ func (exec *HostSession) Transfer(id int, localFilePath string, remoteFilePath s
}
srcFile, err := os.Open(localFilePath)
if err != nil {
result.ErrorInfo=err.Error()
result.ErrorInfo = err.Error()
result.Result = err.Error()
result.Error = err
return result
@ -148,7 +148,7 @@ func (exec *HostSession) Transfer(id int, localFilePath string, remoteFilePath s
// 这里换成实际的 SSH 连接的 用户名密码主机名或IPSSH端口
// create sftp client
if err != nil {
result.ErrorInfo=err.Error()
result.ErrorInfo = err.Error()
result.Result = err.Error()
result.Error = err
return result
@ -157,7 +157,7 @@ func (exec *HostSession) Transfer(id int, localFilePath string, remoteFilePath s
dstFile, err := sftpClient.Create(remoteFilePath)
if err != nil {
result.ErrorInfo=err.Error()
result.ErrorInfo = err.Error()
result.Result = err.Error()
result.Error = err
return result
@ -167,7 +167,7 @@ func (exec *HostSession) Transfer(id int, localFilePath string, remoteFilePath s
//n, err := Copy(dstFile, io.LimitReader(srcFile, fileSize))
n, err := io.Copy(dstFile, io.LimitReader(srcFile, fileSize))
if err != nil {
result.ErrorInfo=err.Error()
result.ErrorInfo = err.Error()
result.Result = err.Error()
result.Error = err
return result
@ -175,7 +175,7 @@ func (exec *HostSession) Transfer(id int, localFilePath string, remoteFilePath s
if n != fileSize {
beego.Info(err)
result.Error = errors.New(fmt.Sprintf("copy: expected %v bytes, got %d", fileSize, n))
result.ErrorInfo=result.Error.Error()
result.ErrorInfo = result.Error.Error()
result.Result = result.Error.Error()
return result
}
@ -203,7 +203,7 @@ func (exec *HostSession) GenerateConfig() ssh.ClientConfig {
Auth: auths,
}
config.Ciphers = []string{"aes128-cbc", "3des-cbc","aes128-ctr","aes192-ctr","aes256-ctr" }
config.Ciphers = []string{"aes128-cbc", "3des-cbc", "aes128-ctr", "aes192-ctr", "aes256-ctr"}
return config
}

View File

@ -2,14 +2,15 @@ package sshexec
import (
"errors"
"github.com/ivpusic/grpool"
"golang.org/x/crypto/ssh"
"io/ioutil"
"log"
"os"
"time"
"strings"
"strconv"
"strings"
"time"
"github.com/ivpusic/grpool"
"golang.org/x/crypto/ssh"
)
//
@ -24,11 +25,13 @@ type SSHExecAgent struct {
func PublicKeyFile(file string) ssh.AuthMethod {
buffer, err := ioutil.ReadFile(file)
if err != nil {
log.Printf("PublicKeyFile err %s \r\n", err.Error())
return nil
}
key, err := ssh.ParsePrivateKey(buffer)
if err != nil {
log.Printf("ParsePrivateKey err %s \r\n", err.Error())
return nil
}
return ssh.PublicKeys(key)
@ -49,6 +52,8 @@ func GetAuthKeys(keys []string) []ssh.AuthMethod {
return methods
}
func (s *SSHExecAgent) SshHostByKey(hosts []string, user string, cmd string) ([]ExecResult, error) {
log.Printf("SshHostByKey %s %+v\r\n ", user, hosts)
if len(hosts) == 0 {
log.Println("no hosts")
return nil, errors.New("no hosts")
@ -76,13 +81,13 @@ func (s *SSHExecAgent) SshHostByKey(hosts []string, user string, cmd string) ([]
pool.JobQueue <- grpool.Job{
Jobid: count,
Jobfunc: func() (interface{}, error) {
hostInfo:=strings.Split(hosts[count],":")
ip:=hostInfo[0]
prot:=22
if len(hostInfo)>1{
hostInfo := strings.Split(hosts[count], ":")
ip := hostInfo[0]
prot := 22
if len(hostInfo) > 1 {
protInt, err := strconv.Atoi(hostInfo[1])
if err==nil{
prot=protInt
if err == nil {
prot = protInt
}
}
@ -126,6 +131,7 @@ func (s *SSHExecAgent) SshHostByKey(hosts []string, user string, cmd string) ([]
}
}
//这里的host要带端口信息
func (s *SSHExecAgent) SftpHostByKey(hosts []string, user string, localFilePath string, remoteFilePath string) ([]ExecResult, error) {
if len(hosts) == 0 {
@ -155,13 +161,13 @@ func (s *SSHExecAgent) SftpHostByKey(hosts []string, user string, localFilePath
pool.JobQueue <- grpool.Job{
Jobid: count,
Jobfunc: func() (interface{}, error) {
hostInfo:=strings.Split(hosts[count],":")
ip:=hostInfo[0]
prot:=22
if len(hostInfo)>1{
hostInfo := strings.Split(hosts[count], ":")
ip := hostInfo[0]
prot := 22
if len(hostInfo) > 1 {
protInt, err := strconv.Atoi(hostInfo[1])
if err==nil{
prot=protInt
if err == nil {
prot = protInt
}
}

View File

@ -57,9 +57,9 @@ func (c *BaseComponents) runLocalCommand(command string) (sshexec.ExecResult, er
*/
func (c *BaseComponents) runRemoteCommand(command string, hosts []string) ([]sshexec.ExecResult, error) {
if len(hosts) == 0 {
hostsInfo:=c.GetHosts()
hostsInfo := c.GetHosts()
for _, info := range hostsInfo {
hosts=append(hosts,info.AllHost)
hosts = append(hosts, info.AllHost)
}
}
id := c.SaveRecord(command)
@ -88,9 +88,9 @@ func (c *BaseComponents) runRemoteCommand(command string, hosts []string) ([]ssh
*/
func (c *BaseComponents) copyFilesBySftp(src string, dest string, hosts []string) ([]sshexec.ExecResult, error) {
if len(hosts) == 0 {
hostsInfo:=c.GetHosts()
hostsInfo := c.GetHosts()
for _, info := range hostsInfo {
hosts=append(hosts,info.AllHost)
hosts = append(hosts, info.AllHost)
}
}
id := c.SaveRecord("Transfer")
@ -121,9 +121,9 @@ func (c *BaseComponents) copyFilesByP2p(id string, src string, dest string, host
rid := c.SaveRecord("Transfer by p2p")
createdAt := int(start.Unix())
if len(hosts) == 0 {
hostsInfo:=c.GetHosts()
hostsInfo := c.GetHosts()
for _, info := range hostsInfo {
hosts=append(hosts,info.Ip)
hosts = append(hosts, info.Ip)
}
}
s, err := gopubssh.TransferByP2p(id, hosts, c.project.ReleaseUser, src, dest, SSHREMOTETIMEOUT)
@ -141,15 +141,13 @@ func (c *BaseComponents) copyFilesByP2p(id string, src string, dest string, host
}
type HostInfo struct {
Ip string
Group int
Port int
Ip string
Group int
Port int
AllHost string
}
/**
* 获取host
*/
@ -163,25 +161,25 @@ func (c *BaseComponents) GetHosts() []HostInfo {
hosts := reg.FindAll([]byte(hostsStr), -1)
res := []HostInfo{}
for _, host := range hosts {
isInList:=false
isInList := false
for _, r := range res {
if r.Ip==string(host){
isInList=true
if r.Ip == string(host) {
isInList = true
}
}
if !isInList {
res = append(res, HostInfo{Ip:string(host),Port:22})
res = append(res, HostInfo{Ip: string(host), Port: 22})
}
}
//格式化端口号
reg1 := regexp.MustCompile(`(\d+)\.(\d+)\.(\d+)\.(\d+)\:(\d+)`)
hosts1 := reg1.FindAll([]byte(hostsStr), -1)
for _, host := range hosts1 {
ip:=strings.Split(string(host),":")[0]
port:=strings.Split(string(host),":")[1]
ip := strings.Split(string(host), ":")[0]
port := strings.Split(string(host), ":")[1]
for i, r := range res {
if r.Ip==ip{
res[i].Port=common.GetInt(port)
if r.Ip == ip {
res[i].Port = common.GetInt(port)
}
}
}
@ -189,50 +187,53 @@ func (c *BaseComponents) GetHosts() []HostInfo {
reg2 := regexp.MustCompile(`(\d+)\#(\d+)\.(\d+)\.(\d+)\.(\d+)`)
hosts2 := reg2.FindAll([]byte(hostsStr), -1)
for _, host := range hosts2 {
ip:=strings.Split(string(host),"#")[1]
group:=strings.Split(string(host),"#")[0]
ip := strings.Split(string(host), "#")[1]
group := strings.Split(string(host), "#")[0]
for i, r := range res {
if r.Ip==ip{
res[i].Group=common.GetInt(group)
if r.Ip == ip {
res[i].Group = common.GetInt(group)
}
}
}
for i, r:= range res {
res[i].AllHost=r.Ip+":"+common.GetString(r.Port)
for i, r := range res {
res[i].AllHost = r.Ip + ":" + common.GetString(r.Port)
}
return res
}
/**
* 获取host ip
*/
func (c *BaseComponents) GetHostIps() []string {
hosts:=[]string{}
hostsInfo:=c.GetHosts()
hosts := []string{}
hostsInfo := c.GetHosts()
for _, info := range hostsInfo {
hosts=append(hosts,info.Ip)
hosts = append(hosts, info.Ip)
}
return hosts
}
/**
* 获取host ip加端口
*/
func (c *BaseComponents) GetAllHost() []string {
hosts:=[]string{}
hostsInfo:=c.GetHosts()
hosts := []string{}
hostsInfo := c.GetHosts()
for _, info := range hostsInfo {
hosts=append(hosts,info.AllHost)
hosts = append(hosts, info.AllHost)
}
return hosts
}
func (c *BaseComponents) GetGroupHost() map[int]string {
hosts:=map[int]string{}
hostsInfo:=c.GetHosts()
hosts := map[int]string{}
hostsInfo := c.GetHosts()
beego.Info(hostsInfo)
for _, info := range hostsInfo {
hosts[info.Group]=info.Ip+":"+common.GetString(info.Port)+"\r\n"
hosts[info.Group] = info.Ip + ":" + common.GetString(info.Port) + "\r\n"
}
return hosts
}
/**
* 获取环境
*/

View File

@ -98,7 +98,7 @@ func (c *BaseComponents) unpackageFiles() error {
//兼容docker
if beego.BConfig.RunMode == "docker" {
cmds = append(cmds, fmt.Sprintf("tar %s %s -C %s", unTarparameter, releasePackage, releasePath))
}else{
} else {
cmds = append(cmds, fmt.Sprintf("tar --preserve-permissions --touch --no-same-owner %s %s -C %s", unTarparameter, releasePackage, releasePath))
}
cmd := strings.Join(cmds, " && ")
@ -123,7 +123,7 @@ func (c *BaseComponents) packageFiles() error {
if beego.BConfig.RunMode == "docker" {
cmds = append(cmds, fmt.Sprintf("tar %s %s %s %s", c.excludes(version), tarparameter, packagePath, commandFiles))
}else{
} else {
cmds = append(cmds, fmt.Sprintf("tar %s --preserve-permissions %s %s %s", c.excludes(version), tarparameter, packagePath, commandFiles))
}
cmd := strings.Join(cmds, " && ")
@ -233,12 +233,12 @@ func (c *BaseComponents) SendP2pAgent(dirAgentPath string, destPath string) erro
return err
}
agentFileConf := "agent.json"
_, err = c.copyFilesBySftp(strings.TrimRight(dirAgentPath, "/")+"/"+agentFileConf, strings.TrimRight(destPath, "/")+"/src/"+agentFileConf,[]string{})
_, err = c.copyFilesBySftp(strings.TrimRight(dirAgentPath, "/")+"/"+agentFileConf, strings.TrimRight(destPath, "/")+"/src/"+agentFileConf, []string{})
if err != nil {
return err
}
controlFile := "control"
_, err = c.copyFilesBySftp(strings.TrimRight(dirAgentPath, "/")+"/"+controlFile, strings.TrimRight(destPath, "/")+"/"+controlFile,[]string{})
_, err = c.copyFilesBySftp(strings.TrimRight(dirAgentPath, "/")+"/"+controlFile, strings.TrimRight(destPath, "/")+"/"+controlFile, []string{})
if err != nil {
return err
}

View File

@ -1,11 +1,11 @@
package components
import (
"strings"
"github.com/bndr/gojenkins"
"github.com/astaxie/beego"
"regexp"
"github.com/bndr/gojenkins"
"net/url"
"regexp"
"strings"
)
type BasJenkins struct {
@ -15,6 +15,7 @@ type BasJenkins struct {
func (c *BasJenkins) SetBaseComponents(b BaseComponents) {
c.baseComponents = b
}
/**
* 获取提交历史
*
@ -29,14 +30,14 @@ func (c *BasJenkins) GetCommitList(count int) ([]JenkinData, error) {
//获取url 和job
var list []JenkinData
u, err := url.Parse(c.baseComponents.project.RepoUrl)
jenkinsUrl:=u.Scheme+"://"+u.Host
jobs := strings.Split(u.Path,"/job/")
job:=strings.Trim(jobs[1],"/")
jenkinsUrl := u.Scheme + "://" + u.Host
jobs := strings.Split(u.Path, "/job/")
job := strings.Trim(jobs[1], "/")
jenkins := gojenkins.CreateJenkins(jenkinsUrl)
_, err = jenkins.Init()
_, err = jenkins.Init()
if err != nil {
beego.Error(err, "Jenkins Initialization failed")
return list,err
return list, err
}
builds, _ := jenkins.GetAllBuildIds(job)
@ -65,7 +66,7 @@ func (c *BasJenkins) GetCommitList(count int) ([]JenkinData, error) {
url := "null"
//var md5 interface{}
url = jenkinsUrl+ build.Base + "/artifact/" + path
url = jenkinsUrl + build.Base + "/artifact/" + path
//md5 = build.Raw.MavenArtifacts
var build_map JenkinData
build_map.Build = the_base_id + "/" + new_path
@ -73,7 +74,5 @@ func (c *BasJenkins) GetCommitList(count int) ([]JenkinData, error) {
//build_map.MD5 = md5
list = append(list, build_map)
}
return list,nil
return list, nil
}

View File

@ -49,7 +49,7 @@ func LocalExec(cmd string) sshexec.ExecResult {
err := execCommand.Run()
if err != nil {
execResult.Error = err
execResult.ErrorInfo=err.Error()
execResult.ErrorInfo = err.Error()
execResult.Result = b1.String()
return execResult
} else {

View File

@ -2,16 +2,16 @@ package main
import (
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"github.com/astaxie/beego/toolbox"
_ "github.com/go-sql-driver/mysql"
"library/p2p/init_sever"
"models"
"os"
"os/signal"
_ "routers"
"syscall"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"github.com/astaxie/beego/toolbox"
_ "github.com/go-sql-driver/mysql"
)
func initArgs() {
@ -38,21 +38,21 @@ func init() {
dbHost := beego.AppConfig.String("mysqlhost")
dbPort := beego.AppConfig.String("mysqlport")
dbName := beego.AppConfig.String("mysqldb")
if beego.BConfig.RunMode == "docker"{
if os.Getenv("MYSQL_USER")!=""{
dbUser=os.Getenv("MYSQL_USER")
if beego.BConfig.RunMode == "docker" {
if os.Getenv("MYSQL_USER") != "" {
dbUser = os.Getenv("MYSQL_USER")
}
if os.Getenv("MYSQL_PASS")!=""{
dbPass=os.Getenv("MYSQL_PASS")
if os.Getenv("MYSQL_PASS") != "" {
dbPass = os.Getenv("MYSQL_PASS")
}
if os.Getenv("MYSQL_HOST")!=""{
dbHost=os.Getenv("MYSQL_HOST")
if os.Getenv("MYSQL_HOST") != "" {
dbHost = os.Getenv("MYSQL_HOST")
}
if os.Getenv("MYSQL_PORT")!=""{
dbPort=os.Getenv("MYSQL_PORT")
if os.Getenv("MYSQL_PORT") != "" {
dbPort = os.Getenv("MYSQL_PORT")
}
if os.Getenv("MYSQL_DB")!=""{
dbName=os.Getenv("MYSQL_DB")
if os.Getenv("MYSQL_DB") != "" {
dbName = os.Getenv("MYSQL_DB")
}
}

View File

@ -16,7 +16,7 @@ func Syncdb() {
beego.Info("数据库初始化开始")
err := createdb()
if err != nil {
beego.Error("数据库创建错误:",err)
beego.Error("数据库创建错误:", err)
return
}
@ -31,7 +31,7 @@ func Syncdb() {
// 遇到错误立即返回
err = orm.RunSyncdb(name, force, verbose)
if err != nil {
beego.Error("数据表创建错误:",err)
beego.Error("数据表创建错误:", err)
}
beego.Info("数据表创建完成")
insertUser()
@ -46,21 +46,21 @@ func Connect() {
dbHost := beego.AppConfig.String("mysqlhost")
dbPort := beego.AppConfig.String("mysqlport")
dbName := beego.AppConfig.String("mysqldb")
if beego.BConfig.RunMode == "docker"{
if os.Getenv("MYSQL_USER")!=""{
dbUser=os.Getenv("MYSQL_USER")
if beego.BConfig.RunMode == "docker" {
if os.Getenv("MYSQL_USER") != "" {
dbUser = os.Getenv("MYSQL_USER")
}
if os.Getenv("MYSQL_PASS")!=""{
dbPass=os.Getenv("MYSQL_PASS")
if os.Getenv("MYSQL_PASS") != "" {
dbPass = os.Getenv("MYSQL_PASS")
}
if os.Getenv("MYSQL_HOST")!=""{
dbHost=os.Getenv("MYSQL_HOST")
if os.Getenv("MYSQL_HOST") != "" {
dbHost = os.Getenv("MYSQL_HOST")
}
if os.Getenv("MYSQL_PORT")!=""{
dbPort=os.Getenv("MYSQL_PORT")
if os.Getenv("MYSQL_PORT") != "" {
dbPort = os.Getenv("MYSQL_PORT")
}
if os.Getenv("MYSQL_DB")!=""{
dbName=os.Getenv("MYSQL_DB")
if os.Getenv("MYSQL_DB") != "" {
dbName = os.Getenv("MYSQL_DB")
}
}
@ -70,14 +70,14 @@ func Connect() {
//utils.Display("dbLink", dbLink)
err := orm.RegisterDriver("mysql", orm.DRMySQL)
if err != nil {
beego.Error("数据库连接错误:",err)
beego.Error("数据库连接错误:", err)
os.Exit(2)
return
}
err = orm.RegisterDataBase("default", "mysql", dbLink, maxIdleConn, maxOpenConn)
orm.Debug = true
if err != nil {
beego.Error("数据库连接错误:",err)
beego.Error("数据库连接错误:", err)
os.Exit(2)
return
}
@ -91,21 +91,21 @@ func createdb() error {
dbHost := beego.AppConfig.String("mysqlhost")
dbPort := beego.AppConfig.String("mysqlport")
dbName := beego.AppConfig.String("mysqldb")
if beego.BConfig.RunMode == "docker"{
if os.Getenv("MYSQL_USER")!=""{
dbUser=os.Getenv("MYSQL_USER")
if beego.BConfig.RunMode == "docker" {
if os.Getenv("MYSQL_USER") != "" {
dbUser = os.Getenv("MYSQL_USER")
}
if os.Getenv("MYSQL_PASS")!=""{
dbPass=os.Getenv("MYSQL_PASS")
if os.Getenv("MYSQL_PASS") != "" {
dbPass = os.Getenv("MYSQL_PASS")
}
if os.Getenv("MYSQL_HOST")!=""{
dbHost=os.Getenv("MYSQL_HOST")
if os.Getenv("MYSQL_HOST") != "" {
dbHost = os.Getenv("MYSQL_HOST")
}
if os.Getenv("MYSQL_PORT")!=""{
dbPort=os.Getenv("MYSQL_PORT")
if os.Getenv("MYSQL_PORT") != "" {
dbPort = os.Getenv("MYSQL_PORT")
}
if os.Getenv("MYSQL_DB")!=""{
dbName=os.Getenv("MYSQL_DB")
if os.Getenv("MYSQL_DB") != "" {
dbName = os.Getenv("MYSQL_DB")
}
}
var dsn string
@ -114,7 +114,7 @@ func createdb() error {
dsn = fmt.Sprintf("%s:%s@tcp(%s:%s)/?charset=utf8", dbUser, dbPass, dbHost, dbPort)
db, err := sql.Open("mysql", dsn)
if err != nil {
beego.Error("数据库连接错误:",err)
beego.Error("数据库连接错误:", err)
os.Exit(2)
//panic(err.Error())
return err
@ -128,7 +128,7 @@ func createdb() error {
return err
} else {
db.Close()
beego.Info("数据库"+dbName+"创建成功")
beego.Info("数据库" + dbName + "创建成功")
return nil
}

View File

@ -8,9 +8,9 @@ import (
"controllers/p2p"
"controllers/record"
"controllers/task"
"controllers/user"
"controllers/walle"
"github.com/astaxie/beego"
"controllers/user"
"github.com/astaxie/beego/plugins/cors"
"time"
)
@ -18,12 +18,12 @@ import (
func init() {
beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
AllowAllOrigins: true,
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin","UserToken", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
ExposeHeaders: []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
MaxAge: 5 * time.Minute,
AllowAllOrigins: true,
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "UserToken", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
ExposeHeaders: []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
MaxAge: 5 * time.Minute,
}))
beego.Router("/login", &controllers.LoginController{})