Skip to content

Instantly share code, notes, and snippets.

@horsley
Last active December 30, 2015 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save horsley/7809080 to your computer and use it in GitHub Desktop.
Save horsley/7809080 to your computer and use it in GitHub Desktop.
go语言版本autodeploy中间件,比较适用于windows服务器直接在php中调用git不灵,本程序自动寻找git执行文件路径,执行git pull,并通过http方式返回结果,带有简单的身份验证
// gitpull project main.go
package main
import (
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"time"
)
func gitPull(o *http.ResponseWriter) bool {
git, err := exec.LookPath("git")
if err != nil {
fmt.Fprint(*o, "git not found!"+err.Error())
return false
}
this, err := exec.LookPath(os.Args[0])
if err != nil {
fmt.Fprint(*o, "get excutable path error!"+err.Error())
return false
}
err = os.Chdir(filepath.Dir(this))
if err != nil {
fmt.Fprint(*o, "chdir error!"+err.Error())
return false
}
cmd := exec.Command(git, "pull")
if os.Getenv("HOME") == "" && os.Getenv("HOMEDIRVE") != "" && os.Getenv("HOMEPATH") != "" {
cmd.Env = []string{"HOME=" + os.Getenv("HOMEDIRVE") + os.Getenv("HOMEPATH")}
}
stdout, err := cmd.StdoutPipe()
if err != nil {
fmt.Fprint(*o, err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
fmt.Fprint(*o, err)
}
err = cmd.Start()
if err != nil {
fmt.Fprint(*o, "run git error!"+err.Error())
return false
}
go io.Copy(*o, stdout)
go io.Copy(*o, stderr)
cmd.Wait()
fmt.Println("Finish autodeploy at " + time.Now().Format("2006-01-02 15:04:05"))
return true
}
func main() {
http.HandleFunc("/", entry)
http.ListenAndServe(":8124", nil)
}
func entry(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") == "" {
w.Header().Set("WWW-Authenticate", "Basic realm=\"My Realm\"")
http.Error(w, "Restrict area", http.StatusUnauthorized)
} else if r.Header.Get("Authorization") == "Basic aG9yc2xleTpnaXQtcHVsbA==" { //horsley:git-pull
gitPull(&w)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment