dimanche 24 novembre 2019

What is wrong with this code? I am trying to test go-chi routes & handlers here

I am trying to test my go-chi routes and the handler functions. I have been using a helper function to run the handlers. This used to work fine in go-gin, and according to what I found the ServeHTTP function in go-chi is also supposed to work the same way. However, I am getting a weird segmentation fault for the same. The way I see, chiR.ServeHTTP(w, req) has only 3 variables that I am creating and all 3 of them chiR, w, req is a valid object.

main.go

package main

import (
    "net/http"

    "github.com/go-chi/chi"
    "github.com/unrolled/render"
)

var op *render.Render

func main() {
    op = render.New(render.Options{
        StreamingJSON: true,
    })
    chiR := chi.NewRouter()
    initRoutes(chiR)
    http.ListenAndServe(":8080", chiR)
}
func initRoutes(chiR *chi.Mux) {
    chiR.Get("/status", cHealthCheck)
}

func cHealthCheck(w http.ResponseWriter, r *http.Request) {
    op.JSON(w, http.StatusOK, map[string]string{"everything": "is ok!"})
}

main_test.go

package main

import (
    "io/ioutil"
    "net/http"
    "net/http/httptest"
    "testing"

    "github.com/go-chi/chi"
    . "github.com/onsi/gomega"
    "github.com/pkg/errors"
)

func TestRouteStatus(t *testing.T) {
    g := NewWithT(t)
    json, err := Http("GET", "/status")
    g.Expect(err).To(BeNil(), "")
    g.Expect(json).ToNot(Equal(""))
}

func Http(verb string, path string) (string, error) {
    req, err := http.NewRequest(verb, path, nil)
    if err != nil {
        return "", errors.Wrap(err, "cannot create HttpRequest")
    }
    chiR := chi.NewRouter()
    w := httptest.NewRecorder()
    initRoutes(chiR)
    chiR.ServeHTTP(w, req)
    p, err := ioutil.ReadAll(w.Body)
    if err != nil {
        return "", errors.Wrap(err, "cannot read response body")
    }
    return string(p), nil
}

I am using go 1.13 and running the code using:

go mod init
go build -o app
./app

which is giving me an HTTP server and it works fine.

However when I try to run my tests with

go test

It's giving me an invalid memory address or nil pointer dereference error, from the ServeHTTP function. What am I doing wrong here?

Aucun commentaire:

Enregistrer un commentaire