Use url.Values for post params

This commit is contained in:
vinchent 2024-07-15 21:36:02 +02:00
parent 4debe0e14e
commit e8390cc51d

View File

@ -3,11 +3,11 @@ package handlers
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"fmt"
"go-udemy-web-1/internal/models" "go-udemy-web-1/internal/models"
"log" "log"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url"
"strconv" "strconv"
"strings" "strings"
"testing" "testing"
@ -211,16 +211,10 @@ var postMakeReservationTests = []struct {
func TestRepository_PostMakeReservation(t *testing.T) { func TestRepository_PostMakeReservation(t *testing.T) {
for _, test := range postMakeReservationTests { for _, test := range postMakeReservationTests {
roomID := 1 roomID := 1
var reqBody string reqBody := url.Values{}
if len(test.reservationInfo) > 0 { if len(test.reservationInfo) > 0 {
if test.reservationInfo[0].key == "room_id" { for _, element := range test.reservationInfo {
roomID, _ = strconv.Atoi(test.reservationInfo[0].value) reqBody.Add(element.key, element.value)
}
reqBody = fmt.Sprintf("%s=%s", test.reservationInfo[0].key,
test.reservationInfo[0].value)
for _, element := range test.reservationInfo[1:] {
reqBody = fmt.Sprintf("%s&%s=%s", reqBody, element.key,
element.value)
if element.key == "room_id" { if element.key == "room_id" {
roomID, _ = strconv.Atoi(element.value) roomID, _ = strconv.Atoi(element.value)
} }
@ -235,7 +229,7 @@ func TestRepository_PostMakeReservation(t *testing.T) {
EndDate: ed, EndDate: ed,
} }
req, _ := http.NewRequest("POST", "/make-reservation", strings.NewReader(reqBody)) req, _ := http.NewRequest("POST", "/make-reservation", strings.NewReader(reqBody.Encode()))
ctx := getCtx(req) ctx := getCtx(req)
req = req.WithContext(ctx) req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
@ -323,15 +317,12 @@ var availabilityJSONTests = []struct {
func Test_AvailabilityJSON(t *testing.T) { func Test_AvailabilityJSON(t *testing.T) {
for _, test := range availabilityJSONTests { for _, test := range availabilityJSONTests {
var reqBody string reqBody := url.Values{}
reqBody = fmt.Sprintf("%s=%s", test.queryInfo[0].key, for _, element := range test.queryInfo {
test.queryInfo[0].value) reqBody.Add(element.key, element.value)
for _, element := range test.queryInfo[1:] {
reqBody = fmt.Sprintf("%s&%s=%s", reqBody, element.key,
element.value)
} }
req, _ := http.NewRequest("POST", "/make-reservation", strings.NewReader(reqBody)) req, _ := http.NewRequest("POST", "/make-reservation", strings.NewReader(reqBody.Encode()))
ctx := getCtx(req) ctx := getCtx(req)
req = req.WithContext(ctx) req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Content-Type", "application/x-www-form-urlencoded")