golang gin testing
package main

import (
	"net/http"
	"github.com/gin-gonic/gin"
)

type LoginInput struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

func Login(c *gin.Context) {

	body := LoginInput{}
	c.ShouldBindJSON(&body)
	c.Set("content-type", "application/json")

	c.JSON(http.StatusOK, gin.H{
		"data": body,
	})
}

func main() {
	router := SetupRouter()
	router.Run()
}

func SetupRouter() *gin.Engine {
	router := gin.Default()
	router.POST("/api/v1/login", Login)

	return router
}

// ==================================================================

package main

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
	"github.com/stretchr/testify/assert"
)

type Response struct {
	Data LoginInput `json:"data"`
}

var router = SetupRouter()

func TestLogin(t *testing.T) {
	t.Run("Example login", func(t *testing.T) {

		payload := LoginInput{}
		payload.Username = "restuwahyu13@gmail.com"
		payload.Password = "qwerty12"

		encoded, err := json.Marshal(payload)

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

		rr := httptest.NewRecorder()
		req, err := http.NewRequest(http.MethodPost, "/api/v1/login", bytes.NewBuffer(encoded))
		req.Header.Set("Content-Type", "application/json")

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

		router.ServeHTTP(rr, req)

		// not with struct
		// res := make(map[string]interface{})
		// json.NewDecoder(rr.Body).Decode(&res)
		// parse := res["data"].(map[string]interface{})

		// assert.Equal(t, rr.Code, 200)
		// assert.Equal(t, parse["username"], "restuwahyu13@gmail.com")
		// assert.Equal(t, parse["password"], "qwerty12")

		// with struct
		resStruct := Response{}
		json.NewDecoder(rr.Body).Decode(&resStruct)

		assert.Equal(t, rr.Code, 200)
		assert.Equal(t, resStruct.Data.Username, "restuwahyu13@gmail.com")
		assert.Equal(t, resStruct.Data.Password, "qwerty12")
	})
}
go gin unit test
follow this my tutorial for simple implementation, easy to undestand

https://github.com/restuwahyu13/gin-unit-testing

Go相关代码片段

go fuck yourself

bun uptrace relation

golang grpc get headers

golang aes encryption

calculate area of circle

go validator regex

consul golang

why you need channel in gorutine

golang blake2s

golang sync condition

golang synchronize

golang synchronization

go tool pprof

go tool golang

golang starvation error

starvation golang error

golang atomic

declare variable without assignment in go

block assignment variables in go

compound assignment variables in go

redis in golang

go router short cut

golang pool

golang semaphore

go back to the previous directory in cmd

golang read from a file

go retry example

Check isset data golang

example context with timeout golang

golang swtich

go channels

Convert type interface{} to Link

how to go to next conflict vimdiff

go run auto reload

compare pointers in go

go https server

go chan example

cmd go to dir

golang field binding

MustBindWith query not work gin

go xorm builder

mac check go version

"[][]byte" in go as multi dimension

how to print all values in slice in go

what is aggregation in mongodb

go lang install

go get minio

todo in golang

how to pronounce government in british

email regex pattern

Go test excute

golang validate phone number

Go read PRIVATE KEY from pem file

golang slice indexof

golang indexof

golang json ignore field

print map in golang

isoString to datetime in golang.

where in postgres database golang

go http hello world code

golang masking phone number

golang replace substring

golang uuid escape

golang connect

get local ip address golang

golang cond

golang remove characters from string

grpc gateway

go grpc protoc

golang push

go to default in switch case

golang channel handling

golang buntdb

go how to make http requests in go

retry request golang

go rabbitmq rpc failover

go new ticker

go ticker sleep deadlock

Define the Chart.yaml file#

http retry request golang