webhook-interceptor/helper.go
2019-12-10 00:04:27 +01:00

87 lines
1.4 KiB
Go

// Copyright (C) 2019 Marius Schellenberger
package main
import (
"encoding/json"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
)
const (
githubAPI = "api/v3"
giteaAPI = "api/v1"
)
func itoa(i int64) string {
return strconv.FormatInt(i, 10)
}
func getNS() (string, error) {
if ns := os.Getenv("POD_NAMESPACE"); ns != "" {
return ns, nil
}
if data, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace"); err == nil {
if ns := strings.TrimSpace(string(data)); len(ns) > 0 {
return ns, nil
}
}
return "default", nil
}
func logError(w http.ResponseWriter, msg string) {
log.Printf("error: %s", msg)
http.Error(w, msg, http.StatusInternalServerError)
}
func contains(a []string, s string) bool {
for _, v := range a {
if v == s {
return true
}
}
return false
}
func getLabel(l string) (label, color string) {
a := strings.SplitN(l, ":", 2)
switch len(a) {
case 1:
label = a[0]
case 2:
label = a[0]
color = a[1]
}
return
}
func detectAPI(r *http.Request) string {
if r.Header.Get(giteaEvent) != "" {
return giteaAPI
}
if r.Header.Get(githubEvent) != "" {
return githubAPI
}
return ""
}
func readBody(r io.ReadCloser, i interface{}) (body []byte, err error) {
defer r.Close()
body, err = ioutil.ReadAll(r)
if err != nil {
return
}
if debug {
log.Printf("debug: %s", string(body))
}
if i != nil {
err = json.Unmarshal(body, i)
}
return
}