package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strings" ) const INDENT = " " func ListenForWebHook(config Config) { http.HandleFunc("/", handleWebHook) err := http.ListenAndServe(config.BindHost+":"+config.BindPort, nil) if err != nil { fmt.Println(err) } } func handleWebHook(writer http.ResponseWriter, request *http.Request) { defer request.Body.Close() data, err := ioutil.ReadAll(request.Body) if err != nil { panic(err) } switch eventType := request.Header.Get("X-Gitea-Event"); eventType { default: fmt.Printf("Unknown event type: %q\n", eventType) handleUnknown(data) case "": // Not a gitea event. fmt.Printf("Got a non-event HTTP request %+v\n", request) case "push": handlePush(data) case "issues": handleIssueAction(data) case "issue_comment": handleIssueComment(data) } } func printSep() { fmt.Println("---") } func handleUnknown(data []byte) { printSep() fmt.Println(string(data)) } func handlePush(data []byte) { printSep() pushData := Push{} json.Unmarshal(data, &pushData) fmt.Printf( "Got a push for repo %q owned by %q. Pushed by %q (%q)\n", pushData.Repository.FullName, pushData.Repository.Owner.Login, pushData.Pusher.Login, pushData.Pusher.Email, ) for _, commit := range pushData.Commits { fmt.Println(INDENT + "--") fmt.Printf( INDENT+"Commit added by %q (%q), made by %q (%q), with hash %q and message:\n", commit.Committer.Name, commit.Committer.Email, commit.Author.Name, commit.Author.Email, commit.Hash, ) msg := strings.Replace(commit.Message, "\n", strings.Repeat(INDENT, 2)+"\n", -1) fmt.Println(strings.Repeat(INDENT, 2) + msg) } } func handleIssueAction(data []byte) { action := IssueAction{} json.Unmarshal(data, &action) printSep() fmt.Printf( "%q (%q) performed the action %q on repo %q and issue %q\n", action.Sender.Login, action.Sender.Email, action.Action, action.Repository.FullName, action.Issue.Title, ) } func handleIssueComment(data []byte) { action := IssueAction{} json.Unmarshal(data, &action) printSep() fmt.Printf( "%q (%q) performed the comment action %q on repo %q and issue %q\n", action.Sender.Login, action.Sender.Email, action.Action, action.Repository.FullName, action.Issue.Title, ) fmt.Printf(INDENT + "---\n") msg := strings.Replace(action.Comment.Body, "\n", strings.Repeat(INDENT, 2) + "\n", -1) fmt.Printf(strings.Repeat(INDENT, 2) + msg) }