Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go - How to test with http.NewRequest

Tags:

go

I've got below code for testing http request:

func TestAuthenticate(t *testing.T) {
    api := &ApiResource{}
    ws := new(restful.WebService)
    ws.Consumes(restful.MIME_JSON, restful.MIME_XML)
    ws.Produces(restful.MIME_JSON, restful.MIME_JSON)
    ws.Route(ws.POST("/login").To(api.Authenticate))
    restful.Add(ws)

    bodyReader := strings.NewReader("<request><Username>42</Username><Password>adasddsa</Password><Channel>M</Channel></request>")

    httpRequest, _ := http.NewRequest("POST", "/login", bodyReader)
//  httpRequest.Header.Set("Content-Type", restful.MIME_JSON)
    httpRequest.Header.Set("Content-Type", restful.MIME_XML)
    httpWriter := httptest.NewRecorder()

    restful.DefaultContainer.ServeHTTP(httpWriter, httpRequest)
}

I tried to use json as a string with same NewReader and also tried to use struct with json.Marshal.

Neither of them works.

Is there a method where I can code bodyReader for a valid third parameter for http.NewRequest?

Similar request as input for NewReader in JSON is:

bodyReader := strings.NewReader("{'Username': '12124', 'Password': 'testinasg', 'Channel': 'M'}")

Struct fields are is: Username, Password, Channel

like image 893
Passionate Engineer Avatar asked Oct 12 '14 01:10

Passionate Engineer


1 Answers

The JSON is invalid. JSON uses " for quoting strings, not '.

Use this line of code to create the request body:

bodyReader := strings.NewReader(`{"Username": "12124", "Password": "testinasg", "Channel": "M"}`)

I used a raw string literal to avoid quoting the " in the JSON text.

like image 166
Bayta Darell Avatar answered Oct 10 '22 06:10

Bayta Darell