Validation

Mahakam has a validation middleware that you can use to validate the request body. What you actually need to use is just implement extensions.Validation struct.

// Validation is an interface that requires a Validate method for validating request data using ValidationMiddleware.
type Validation interface {
	Validate() error
}

Example

Here is an minimal example of a validation middleware.

package main

import (
	"net/http"

	"github.com/seiortech/mahakam"
	"github.com/seiortech/mahakam/extensions"
)

type LoginRequest struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

func (r LoginRequest) Validate() error {
	errorMap := make(map[string]any)
	if r.Email == "" {
		errorMap["email"] = "Email is required"
	}

	if r.Password == "" {
		errorMap["password"] = "Password is required"
	}

	if len(errorMap) > 0 {
		return extensions.ValidationError{
			Message: "Invalid request body",
			Code:    http.StatusBadRequest,
			Fields:  errorMap,
		}
	}

	return nil
}

func main() {
	mux := http.NewServeMux()

	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "public/index.html")
	})

	mux.HandleFunc("POST /login", extensions.ValidationMiddleware[LoginRequest](func(w http.ResponseWriter, r *http.Request) {
		body := r.Context().Value(extensions.BodyKey).(LoginRequest) // get the request body from the context

		// Here you would typically handle the login logic, e.g., checking credentials.
		// For demonstration, we just return a success message.
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("Login successful for " + body.Email))
	}))

	server := mahakam.NewServer(":8080", mux)

	if err := server.ListenAndServe(); err != nil {
		panic(err)
	}
}
💡 Tip
Since you need to implement the validation() function itself. It means can use library like go-playground/validator or go-ozzo/ozzo-validation to validate the request body.