func TestLoginUnauthenticated(t *testing.T) {
	w := httptest.NewRecorder()
	r := getRouter(true)
	r.POST("/u/login", ensureNotLoggedIn(), performLogin)
	loginPayload := getLoginPOSTPayload()
	req, _ := http.NewRequest("POST", "/u/login", strings.NewReader(loginPayload))
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Add("Content-Length", strconv.Itoa(len(loginPayload)))
	r.ServeHTTP(w, req)
	if w.Code != http.StatusOK {
		t.Fail()
	}
	p, err := ioutil.ReadAll(w.Body)
	if err != nil || strings.Index(string(p), "<title>Successful Login</title>") < 0 {
		t.Fail()
	}
}
Test that a POST request to login returns a success message for
an unauthenticated user
package main
import (
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strconv"
	"strings"
	"testing"
)
func TestShowLoginPageAuthenticated(t *testing.T) {
	w := httptest.NewRecorder()
	r := getRouter(true)
	http.SetCookie(w, &http.Cookie{Name: "token", Value: "123"})
	r.GET("/u/login", ensureNotLoggedIn(), showLoginPage)
	req, _ := http.NewRequest("GET", "/u/login", nil)
	req.Header = http.Header{"Cookie": w.HeaderMap["Set-Cookie"]}
	r.ServeHTTP(w, req)
	if w.Code != http.StatusUnauthorized {
		t.Fail()
	}
}
func TestShowLoginPageUnauthenticated(t *testing.T) {
	r := getRouter(true)
	r.GET("/u/login", ensureNotLoggedIn(), showLoginPage)
	req, _ := http.NewRequest("GET", "/u/login", nil)
	testHTTPResponse(t, r, req, func(w *httptest.ResponseRecorder) bool {
		statusOK := w.Code == http.StatusOK
		p, err := ioutil.ReadAll(w.Body)
		pageOK := err == nil && strings.Index(string(p), "<title>Login</title>") > 0
		return statusOK && pageOK
	})
}
func TestLoginAuthenticated(t *testing.T) {
	w := httptest.NewRecorder()
	r := getRouter(true)
	http.SetCookie(w, &http.Cookie{Name: "token", Value: "123"})
	r.POST("/u/login", ensureNotLoggedIn(), performLogin)
	loginPayload := getLoginPOSTPayload()
	req, _ := http.NewRequest("POST", "/u/login", strings.NewReader(loginPayload))
	req.Header = http.Header{"Cookie": w.HeaderMap["Set-Cookie"]}
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Add("Content-Length", strconv.Itoa(len(loginPayload)))
	r.ServeHTTP(w, req)
	if w.Code != http.StatusUnauthorized {
		t.Fail()
	}
}