tripwire/util.go
2022-06-25 11:25:08 -04:00

69 lines
1.4 KiB
Go

package main
import (
"encoding/json"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"runtime/debug"
)
func sendJSON(w http.ResponseWriter, jsonMessage interface{}) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(jsonMessage)
}
func sendError(w http.ResponseWriter, err YggError) {
if config.DebugMode {
log.Printf("Send error: %s\n", err.ErrorMessage)
}
w.WriteHeader(err.Code)
sendJSON(w, err)
}
func unmarshalTo(r *http.Request, v any) error {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
err = json.Unmarshal(body, &v)
if err != nil {
return err
}
return nil
}
func handleError(w http.ResponseWriter, err error) {
sendError(w, YggError{Code: 500, Error: "Unspecified error", ErrorMessage: "An error has occured handling your request."})
log.Println("error processing request:", err)
if config.DebugMode {
debug.PrintStack()
}
}
func sendEmpty(w http.ResponseWriter) {
w.WriteHeader(http.StatusNoContent)
}
func recievePNG(filename string, w http.ResponseWriter, r *http.Request) ([]byte, *multipart.FileHeader, error) {
file, header, err := r.FormFile(filename)
if err != nil {
return []byte{}, header, err
}
bytes, err := ioutil.ReadAll(file)
if err != nil {
return bytes, header, err
}
if len(bytes) < 4 ||
bytes[0] != 0x89 ||
bytes[1] != 0x50 ||
bytes[2] != 0x4e ||
bytes[3] != 0x47 {
return bytes, header, &InvalidDataError{}
}
return bytes, header, nil
}