diff --git a/bots-common/listen.go b/bots-common/listen.go new file mode 100644 index 0000000..c4ef0c2 --- /dev/null +++ b/bots-common/listen.go @@ -0,0 +1,67 @@ +package common + +import ( + "log" + "net/http" + "net/url" +) + +const RequestType_Push = "push" +const RequestType_Repository = "repository" + +type RequestProcessor func(*RequestHandler) error + +type ListenDefinitions struct { + GitAuthor, Url string + Handlers map[string]RequestProcessor +} + +func StartServer(listenDefs ListenDefinitions) { + if listenDefs.Url != url.PathEscape(listenDefs.Url) { + log.Fatalf("Invalid Url fragment (%s) to listen on. Aborting", listenDefs.Url) + } + + http.HandleFunc("/"+listenDefs.Url, func(res http.ResponseWriter, req *http.Request) { + h := CreateRequestHandler(listenDefs.GitAuthor, listenDefs.Url) + // defer h.Close() + + if len(req.Header.Get("Content-Type")) == 0 || + req.Header["Content-Type"][0] != "application/json" || + req.Method != "POST" { + + h.WriteError() + res.WriteHeader(http.StatusInternalServerError) + return + } + + hdr := req.Header[GiteaRequestHeader] + if len(hdr) != 1 { + h.LogError("Unsupported number of %s headers: %d: %#v\n", GiteaRequestHeader, len(hdr), hdr) + h.WriteError() + res.WriteHeader(http.StatusInternalServerError) + return + } + reqType := hdr[0] + + if handler, ok := listenDefs.Handlers[reqType]; ok { + if err := handler(h); err != nil { + h.LogError("error in handler for %s: %v", reqType, err); + res.WriteHeader(http.StatusInternalServerError) + return + } + } else { + h.LogError("Unsupported request type: %s", reqType) + res.WriteHeader(http.StatusInternalServerError) + } + + if h.HasError() { + h.WriteError() + res.WriteHeader(http.StatusInternalServerError) + return + } + res.Header().Add("Content-Type", "application/json") + res.WriteHeader(http.StatusOK) + }) + + log.Fatal(http.ListenAndServe("[::1]:8000", nil)) +} diff --git a/bots-common/tokens.go b/bots-common/tokens.go new file mode 100644 index 0000000..47481c7 --- /dev/null +++ b/bots-common/tokens.go @@ -0,0 +1,28 @@ +package common + +import ( + "errors" + "fmt" + "os" +) + +var giteaToken, obsToken string + +func RequireGiteaSecretToken() error { + giteaToken = os.Getenv(GiteaTokenEnv) + if len(giteaToken) < 10 { + return errors.New(GiteaTokenEnv + " not provided") + } + + err := os.Setenv(GiteaTokenEnv, "") + if err != nil { + return fmt.Errorf("%s: %v", "Cannot reset "+GiteaTokenEnv, err) + } + + return nil +} + +func RequireObsSecretToken() error { + return nil +} +