Semaphore/api/helpers/helpers.go

110 lines
2.2 KiB
Go
Raw Normal View History

package helpers
2016-01-05 00:32:53 +01:00
import (
"crypto/md5"
"encoding/json"
"fmt"
"io"
2017-02-23 00:21:49 +01:00
"net/http"
2021-10-13 16:33:07 +02:00
"net/url"
"os"
"runtime/debug"
2016-01-05 00:32:53 +01:00
"strconv"
"strings"
log "github.com/Sirupsen/logrus"
"github.com/gorilla/context"
"github.com/ansible-semaphore/semaphore/db"
"github.com/gorilla/mux"
2016-01-05 00:32:53 +01:00
)
func Store(r *http.Request) db.Store {
return context.Get(r, "store").(db.Store)
}
2017-02-22 23:17:36 +01:00
func isXHR(w http.ResponseWriter, r *http.Request) bool {
accept := r.Header.Get("Accept")
return !strings.Contains(accept, "text/html")
2016-01-05 00:32:53 +01:00
}
// GetIntParam fetches a parameter from the route variables as an integer
// redirects to a 404 or writes bad request state depending on error state
2017-02-22 23:17:36 +01:00
func GetIntParam(name string, w http.ResponseWriter, r *http.Request) (int, error) {
2017-02-23 00:21:49 +01:00
intParam, err := strconv.Atoi(mux.Vars(r)[name])
2016-01-05 00:32:53 +01:00
if err != nil {
if !isXHR(w, r) {
2017-02-23 00:21:49 +01:00
http.Redirect(w, r, "/404", http.StatusFound)
2016-01-05 00:32:53 +01:00
} else {
2017-02-22 23:17:36 +01:00
w.WriteHeader(http.StatusBadRequest)
2016-01-05 00:32:53 +01:00
}
return 0, err
}
return intParam, nil
}
//H just a string-to-anything map
type H map[string]interface{}
//Bind decodes json into object
func Bind(w http.ResponseWriter, r *http.Request, out interface{}) bool {
err := json.NewDecoder(r.Body).Decode(out)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
}
return err == nil
}
//WriteJSON writes object as JSON
func WriteJSON(w http.ResponseWriter, code int, out interface{}) {
w.Header().Set("content-type", "application/json")
w.WriteHeader(code)
if err := json.NewEncoder(w).Encode(out); err != nil {
panic(err)
}
}
func WriteError(w http.ResponseWriter, err error) {
if err == db.ErrNotFound {
w.WriteHeader(http.StatusNotFound)
return
}
if err == db.ErrInvalidOperation {
w.WriteHeader(http.StatusConflict)
return
}
log.Error(err)
debug.PrintStack()
w.WriteHeader(http.StatusInternalServerError)
}
func GetMD5Hash(filepath string) (string, error) {
file, err := os.Open(filepath)
if err != nil {
return "", err
}
defer file.Close()
hash := md5.New()
if _, err := io.Copy(hash, file); err != nil {
return "", err
}
return fmt.Sprintf("%x", hash.Sum(nil)), nil
}
2021-10-13 16:33:07 +02:00
func QueryParams(url *url.URL) db.RetrieveQueryParams {
return db.RetrieveQueryParams{
SortBy: url.Query().Get("sort"),
SortInverted: url.Query().Get("order") == "desc",
}
}