webhook-interceptor/helper.go
2019-12-04 17:42:30 +01:00

68 lines
1.2 KiB
Go

// Copyright (C) 2019 Marius Schellenberger
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
)
const (
githubAPI = "api/v3"
giteaAPI = "api/v1"
)
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 strings.Contains(s, v) {
return true
}
}
return false
}
func detectAPI(r *http.Request) string {
if r.Header.Get(giteaEvent) != "" {
return giteaAPI
}
if r.Header.Get(githubEvent) != "" {
return githubAPI
}
return ""
}
func readBody(r *http.Request, i interface{}) (body []byte, err error) {
defer r.Body.Close()
body, err = ioutil.ReadAll(r.Body)
if err != nil {
return
}
if debug {
log.Printf("debug headers: %#v", r.Header)
log.Printf("debug: %s", string(body))
}
err = json.Unmarshal(body, i)
return
}