1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
| package main
import ( "encoding/json" "fmt" "io/ioutil" "net/http" "os" "os/exec" "path/filepath" "strings" "time" )
type Hook struct { Password string `json:"password"` HookName string `json:"hook_name"` }
Config */ type Config struct { Port string `json:"port"` Info []Info `json:"info"` }
Info */ type Info struct { Author string `json:"author"` Password string `json:"password"` Command string `json:"command"` }
var config = Config{}
var info = Info{}
var current_path string
func GetCurrPath() { file, _ := exec.LookPath(os.Args[0]) path, _ := filepath.Abs(file) index := strings.LastIndex(path, string(os.PathSeparator)) current_path = path[:index] + "/" }
func write_log(log string, msg string) { if !file_exist(current_path + log) { os.Create(current_path + log) } f, err := os.OpenFile(current_path+log, os.O_APPEND|os.O_WRONLY, 0644) check(err) defer f.Close() timestamp := time.Now().Unix() tm := time.Unix(timestamp, 0) t := tm.Format("2006-01-02 03:04:05 PM Monday") f.WriteString("\n===== Log start " + t + " =====\n") f.WriteString(msg) f.WriteString("\n===== Log end =====\n")
}
func file_exist(filename string) bool { _, err := os.Stat(filename) return err == nil || os.IsExist(err) }
func check(e error) { defer func() { if err := recover(); err != nil { msg, ok := err.(string) if ok { write_log("deploy_error.log", msg) } write_log("deploy_error.log", e.Error()) } }() if e != nil { panic(e) } }
func exec_deploy() { cmd := exec.Command(info.Command) out, err := cmd.CombinedOutput() check(err) write_log(info.Author+"_deploy.log", string(out)) }
func deploy(w http.ResponseWriter, r *http.Request) { r.ParseForm() fmt.Fprintf(w, "success!") }
func hooks(w http.ResponseWriter, r *http.Request) { r.ParseForm() hook := Hook{} fmt.Println(strings.Join(r.Form["hook"], "")) err := json.Unmarshal([]byte(strings.Join(r.Form["hook"], "")), &hook) check(err) result := checkInfo(hook.Password) if result { go exec_deploy() fmt.Fprintf(w, "success!") } else { fmt.Fprintf(w, "error, the pwd is not right!") } }
func getConfig() { buff, err := ioutil.ReadFile(current_path + "config.json") check(err) err = json.Unmarshal(buff, &config) check(err) }
func checkInfo(password string) bool {
for i := 0; i < len(config.Info); i++ { if config.Info[i].Password == password { info = config.Info[i] return true } } return false }
func main() { GetCurrPath() getConfig() http.HandleFunc("/deploy", deploy) http.HandleFunc("/hooks", hooks) err := http.ListenAndServe(":"+config.Port, nil) check(err) }
|