Gleaner 1: Unit tests

Golang unit tests require the code file to end with _test, the unit Test method to start with Test, and the parameter to be of type * testing.t. Here is a tool kit for calculating hash values and corresponding unit tests.

hashUtils.go

package utils

import (
	"crypto/md5"
	"crypto/sha1"
	"fmt"
)

func Md5(str string) string {
	data := []byte(str)
	has := md5.Sum(data)
	return fmt.Sprintf("%X", has)
}

func SHA1(data []byte) []byte {
	h := sha1.New()
	h.Write(data)
	return h.Sum(nil)}Copy the code

hashUtils_test.go

package utils

import (
	"fmt"
	"testing"
)

func TestMd5(t *testing.T) {
	content := "123456"
	md5 := Md5(content)

	if "E10ADC3949BA59ABBE56E057F20F883E"! = md5 { t.Errorf("md5 failed")}}func TestSHA1(t *testing.T) {
	content := "123456"
	sha1 := fmt.Sprintf("%x", SHA1([]byte(content)))

	if "7c4a8d09ca3762af61e59520943dc26494f8941b"! = sha1 { t.Errorf("sha1 failed")}}Copy the code

In addition to testing this logical code, we also need to test the HTTP request response. Gin recommends testing HTTP-related code using net/ HTTP /httptest.

Start a Gin server main.go

package main

func setupRouter() *gin.Engine {
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		c.String(200, "pong")
	})
	return r
}

func main() {
	r := setupRouter()
	r.Run(":8080")
}
Copy the code

Unit test main_test.go

package main

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

	"github.com/stretchr/testify/assert"
)

func TestPingRoute(t *testing.T) {
	router := setupRouter()

	w := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/ping", nil)
	router.ServeHTTP(w, req)

	assert.Equal(t, 200, w.Code)
	assert.Equal(t, "pong", w.Body.String())
}
Copy the code

Gleaner 2: routes

Look at the code

userRouter := router.Group(`users`)
{
	userRouter.GET(`/`, userHandler.UserList)
}
Copy the code

We declare the route /users/, which is a Web Api, and the url that we pass in is something like /users/, right? PageIndex = 1 & pageSize = 10. User access /users? PageIndex =1&pageSize=10 can also return data normally, this is because Gin helped us to make a 301 jump, the problem is here. Our route is Web Api and the user could be a JS front-end or some other business system. What if the user does not support a 301 redirect?

In fact, we can solve the problem by adding an empty route.

userRouter := router.Group(`users`)
{
	userRouter.GET(` `, userHandler.UserList)
	userRouter.GET(` / `, userHandler.UserList)
}
Copy the code

Now regardless of the user access /users/? PageIndex =1&pageSize=10 or access /users? PageIndex =1&pageSize=10 will get the correct result.

Golang Web Development based on GIN: Gin technology pickup