Testing static files in go and getting the right path

I am a newbie in go an I am trying with this tutorial (https://www.sohamkamani.com/golang/how-to-build-a-web-application/#testing-the-static-file-server) to understand how i write a test for the static files. I modified the project a bit and these all work right but if I shift the test into a tests-folder I get a 404 not found error because the index.html under assets is not found.

fmt.Println(resp);

&{404 Not Found 404 HTTP/1.1 1 1 map[Content-Length:[19] Content-Type:[text/plain; charset=utf-8] Date:[Fri, 22 Apr 2022 12:40:07 GMT] X-Content-Type-Options:[nosniff]] 0xc0001a0080 19 [] false false map[] 0xc00012c100 <nil>}

But if I copy the assests folder into the tests-folder I have no error. My project is structured as follows:

MyProject
tests
---main_test.go
assets
---index.html
handler
---handlers.go
mainfunc
---funcs.go (newRouter()-function goes hier)
main.go
go.mod

I think that I have a problem with:

resp, err := http.Get(mockServer.URL + "/assets/")

How can I set the right path here?

UPDATE

tests/main_test.go

import (
	m "myproject/mainfunc"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestStaticFileServer(t *testing.T) {
	r := m.NewRouter()
	mockServer := httptest.NewServer(r)
	defer mockServer.Close()

	resp, err := http.Get(mockServer.URL + "/assets/")

	if err != nil {
		t.Fatal(err)
	}

    // ERROR HERE
	if resp.StatusCode != http.StatusOK {
		t.Errorf("Status should be 200, got %d", resp.StatusCode)
	}

	contentType := resp.Header.Get("Content-Type")
	expectedContentType := "text/html; charset=utf-8"

    // ERROR HERE
	if expectedContentType != contentType {
		t.Errorf("Wrong content type, expected %s, got %s", expectedContentType, contentType)
	}
}

mainfunc/funcs.go

import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
	h "myproject/handler"
)

func NewRouter() *mux.Router {
	r := mux.NewRouter()
	r.HandleFunc("/hello", Handler).Methods("GET")

	staticFileDirectory := http.Dir("./assets/")
	staticFileHandler := http.StripPrefix("/assets/", http.FileServer(staticFileDirectory))

	r.PathPrefix("/assets/").Handler(staticFileHandler).Methods("GET")

	r.HandleFunc("/bird", h.GetBirdHandler).Methods("GET")
	r.HandleFunc("/bird", h.CreateBirdHandler).Methods("POST")
	
	return r
}

Thanks

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.