This commit is contained in:
Adam Majer 2024-07-08 17:14:26 +02:00
parent 8639c53977
commit a82ae14c34
2 changed files with 95 additions and 0 deletions

67
bots-common/listen.go Normal file
View File

@ -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))
}

28
bots-common/tokens.go Normal file
View File

@ -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
}