Browse Source

RespondAsBadRequest, RespondAsMethodNotAllowed

Volodymyr Tkach 2 years ago
parent
commit
dde3ce42e0
1 changed files with 24 additions and 0 deletions
  1. 24 0
      utils/http/helpers/helpers.go

+ 24 - 0
utils/http/helpers/helpers.go

@@ -6,6 +6,7 @@ import (
 	"net/http"
 	"os"
 	"regexp"
+	"strconv"
 
 	"github.com/vladimirok5959/golang-server-sessions/session"
 )
@@ -21,6 +22,11 @@ func MinifyHtmlCode(str string) string {
 	return str
 }
 
+// Example:
+//
+// sess := helpers.SessionStart(w, r)
+//
+// defer sess.Close()
 func SessionStart(w http.ResponseWriter, r *http.Request) (*session.Session, error) {
 	sess, err := session.New(w, r, "/tmp")
 	if err != nil && !errors.Is(err, os.ErrNotExist) {
@@ -28,3 +34,21 @@ func SessionStart(w http.ResponseWriter, r *http.Request) (*session.Session, err
 	}
 	return sess, err
 }
+
+func RespondAsBadRequest(w http.ResponseWriter, r *http.Request, err error) {
+	if err != nil {
+		log.Printf("%s\n", err.Error())
+		w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
+		w.Header().Set("Content-Type", "application/json")
+		w.WriteHeader(http.StatusBadRequest)
+		if _, e := w.Write([]byte(`{"error":"` + strconv.Quote(err.Error()) + `"}`)); e != nil {
+			log.Printf("%s\n", e.Error())
+		}
+	} else {
+		w.WriteHeader(http.StatusBadRequest)
+	}
+}
+
+func RespondAsMethodNotAllowed(w http.ResponseWriter, r *http.Request) {
+	w.WriteHeader(http.StatusMethodNotAllowed)
+}