github.com/angryronald/go-kit@v0.0.0-20240505173814-ff2bd9c79dbf/net/http/request.middleware_test.go (about)

     1  package http
     2  
     3  import (
     4  	"net/http"
     5  	"net/http/httptest"
     6  	"os"
     7  	"testing"
     8  
     9  	"github.com/angryronald/go-kit/appcontext"
    10  	"github.com/angryronald/go-kit/constant"
    11  )
    12  
    13  func TestLoadEnvironmentIntoRequest(t *testing.T) {
    14  	// Create a new request
    15  	req, err := http.NewRequest("GET", "/", nil)
    16  	if err != nil {
    17  		t.Fatal(err)
    18  	}
    19  
    20  	// Create a recorder to capture the response
    21  	rr := httptest.NewRecorder()
    22  
    23  	os.Setenv(constant.ENVIRONMENT_KEY, string(constant.PRODUCTION))
    24  
    25  	// Create a handler using the LoadEnvironmentIntoRequest middleware
    26  	handler := LoadEnvironmentIntoRequest(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    27  		env := appcontext.Environment(r.Context())
    28  		if env != string(constant.PRODUCTION) {
    29  			t.Errorf("Expected environment to be production, got %s", env)
    30  		}
    31  	}))
    32  
    33  	// Serve the request to the handler
    34  	handler.ServeHTTP(rr, req)
    35  }