本文整理匯總了Golang中github.com/mholt/caddy/middleware.HandlerFunc函數的典型用法代碼示例。如果您正苦於以下問題:Golang HandlerFunc函數的具體用法?Golang HandlerFunc怎麽用?Golang HandlerFunc使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了HandlerFunc函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: nextFunc
func nextFunc(shouldGzip bool) middleware.Handler {
return middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
if shouldGzip {
if r.Header.Get("Accept-Encoding") != "" {
return 0, fmt.Errorf("Accept-Encoding header not expected")
}
if w.Header().Get("Content-Encoding") != "gzip" {
return 0, fmt.Errorf("Content-Encoding must be gzip, found %v", r.Header.Get("Content-Encoding"))
}
if _, ok := w.(gzipResponseWriter); !ok {
return 0, fmt.Errorf("ResponseWriter should be gzipResponseWriter, found %T", w)
}
return 0, nil
}
if r.Header.Get("Accept-Encoding") == "" {
return 0, fmt.Errorf("Accept-Encoding header expected")
}
if w.Header().Get("Content-Encoding") == "gzip" {
return 0, fmt.Errorf("Content-Encoding must not be gzip, found gzip")
}
if _, ok := w.(gzipResponseWriter); ok {
return 0, fmt.Errorf("ResponseWriter should not be gzipResponseWriter")
}
return 0, nil
})
}
示例2: GET
// GET handles the GET method on browse page
func GET(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error) {
functions := template.FuncMap{
"CanBeEdited": utils.CanBeEdited,
"Defined": utils.Defined,
}
tpl, err := utils.GetTemplate(r, functions, "browse")
if err != nil {
return http.StatusInternalServerError, err
}
b := browse.Browse{
Next: middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
return 404, nil
}),
Root: c.Path,
Configs: []browse.Config{
{
PathScope: "/",
Variables: c,
Template: tpl,
},
},
IgnoreIndexes: true,
}
return b.ServeHTTP(w, r)
}
示例3: TestExpVar
func TestExpVar(t *testing.T) {
rw := ExpVar{
Next: middleware.HandlerFunc(contentHandler),
Resource: "/d/v",
}
tests := []struct {
from string
result int
}{
{"/d/v", 0},
{"/x/y", http.StatusOK},
}
for i, test := range tests {
req, err := http.NewRequest("GET", test.from, nil)
if err != nil {
t.Fatalf("Test %d: Could not create HTTP request %v", i, err)
}
rec := httptest.NewRecorder()
result, err := rw.ServeHTTP(rec, req)
if err != nil {
t.Fatalf("Test %d: Could not ServeHTTP %v", i, err)
}
if result != test.result {
t.Errorf("Test %d: Expected Header '%d' but was '%d'",
i, test.result, result)
}
}
}
示例4: TestBrowseTemplate
func TestBrowseTemplate(t *testing.T) {
tmpl, err := template.ParseFiles("testdata/photos.tpl")
if err != nil {
t.Fatalf("An error occured while parsing the template: %v", err)
}
b := Browse{
Next: middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
t.Fatalf("Next shouldn't be called")
return 0, nil
}),
Root: "./testdata",
Configs: []Config{
{
PathScope: "/photos",
Template: tmpl,
},
},
}
req, err := http.NewRequest("GET", "/photos/", nil)
if err != nil {
t.Fatalf("Test: Could not create HTTP request: %v", err)
}
rec := httptest.NewRecorder()
code, err := b.ServeHTTP(rec, req)
if code != http.StatusOK {
t.Fatalf("Wrong status, expected %d, got %d", http.StatusOK, code)
}
respBody := rec.Body.String()
expectedBody := `<!DOCTYPE html>
<html>
<head>
<title>Template</title>
</head>
<body>
<h1>Header</h1>
<h1>/photos/</h1>
<a href="./test.html">test.html</a><br>
<a href="./test2.html">test2.html</a><br>
<a href="./test3.html">test3.html</a><br>
</body>
</html>
`
if respBody != expectedBody {
t.Fatalf("Expected body: %v got: %v", expectedBody, respBody)
}
}
示例5: genErrorHandler
func genErrorHandler(status int, err error, body string) middleware.Handler {
return middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
if len(body) > 0 {
w.Header().Set("Content-Length", strconv.Itoa(len(body)))
fmt.Fprint(w, body)
}
return status, err
})
}
示例6: TestBasicAuth
func TestBasicAuth(t *testing.T) {
rw := BasicAuth{
Next: middleware.HandlerFunc(contentHandler),
Rules: []Rule{
{Username: "test", Password: PlainMatcher("ttest"), Resources: []string{"/testing"}},
},
}
tests := []struct {
from string
result int
cred string
}{
{"/testing", http.StatusUnauthorized, "ttest:test"},
{"/testing", http.StatusOK, "test:ttest"},
{"/testing", http.StatusUnauthorized, ""},
}
for i, test := range tests {
req, err := http.NewRequest("GET", test.from, nil)
if err != nil {
t.Fatalf("Test %d: Could not create HTTP request %v", i, err)
}
auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(test.cred))
req.Header.Set("Authorization", auth)
rec := httptest.NewRecorder()
result, err := rw.ServeHTTP(rec, req)
if err != nil {
t.Fatalf("Test %d: Could not ServeHTTP %v", i, err)
}
if result != test.result {
t.Errorf("Test %d: Expected Header '%d' but was '%d'",
i, test.result, result)
}
if result == http.StatusUnauthorized {
headers := rec.Header()
if val, ok := headers["Www-Authenticate"]; ok {
if val[0] != "Basic" {
t.Errorf("Test %d, Www-Authenticate should be %s provided %s", i, "Basic", val[0])
}
} else {
t.Errorf("Test %d, should provide a header Www-Authenticate", i)
}
}
}
}
示例7: nextFunc
func nextFunc(shouldMime bool, contentType string) middleware.Handler {
return middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
if shouldMime {
if w.Header().Get("Content-Type") != contentType {
return 0, fmt.Errorf("expected Content-Type: %v, found %v", contentType, r.Header.Get("Content-Type"))
}
return 0, nil
}
if w.Header().Get("Content-Type") != "" {
return 0, fmt.Errorf("Content-Type header not expected")
}
return 0, nil
})
}
示例8: TestHeaders
func TestHeaders(t *testing.T) {
hostname, err := os.Hostname()
if err != nil {
t.Fatalf("Could not determine hostname: %v", err)
}
for i, test := range []struct {
from string
name string
value string
}{
{"/a", "Foo", "Bar"},
{"/a", "Bar", ""},
{"/a", "Baz", ""},
{"/a", "ServerName", hostname},
{"/b", "Foo", ""},
{"/b", "Bar", "Removed in /a"},
} {
he := Headers{
Next: middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
return 0, nil
}),
Rules: []Rule{
{Path: "/a", Headers: []Header{
{Name: "Foo", Value: "Bar"},
{Name: "ServerName", Value: "{hostname}"},
{Name: "-Bar"},
}},
},
}
req, err := http.NewRequest("GET", test.from, nil)
if err != nil {
t.Fatalf("Test %d: Could not create HTTP request: %v", i, err)
}
rec := httptest.NewRecorder()
rec.Header().Set("Bar", "Removed in /a")
he.ServeHTTP(rec, req)
if got := rec.Header().Get(test.name); got != test.value {
t.Errorf("Test %d: Expected %s header to be %q but was %q",
i, test.name, test.value, got)
}
}
}
示例9: TestResponseFilterWriter
func TestResponseFilterWriter(t *testing.T) {
tests := []struct {
body string
shouldCompress bool
}{
{"Hello\t\t\t\n", false},
{"Hello the \t\t\t world is\n\n\n great", true},
{"Hello \t\t\nfrom gzip", true},
{"Hello gzip\n", false},
}
filters := []ResponseFilter{
LengthFilter(15),
}
server := Gzip{Configs: []Config{
{ResponseFilters: filters},
}}
for i, ts := range tests {
server.Next = middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
w.Header().Set("Content-Length", fmt.Sprint(len(ts.body)))
w.Write([]byte(ts.body))
return 200, nil
})
r := urlRequest("/")
r.Header.Set("Accept-Encoding", "gzip")
w := httptest.NewRecorder()
server.ServeHTTP(w, r)
resp := w.Body.String()
if !ts.shouldCompress {
if resp != ts.body {
t.Errorf("Test %v: No compression expected, found %v", i, resp)
}
} else {
if resp == ts.body {
t.Errorf("Test %v: Compression expected, found %v", i, resp)
}
}
}
}
示例10: TestRedirect
func TestRedirect(t *testing.T) {
for i, test := range []struct {
from string
expectedLocation string
}{
{"/from", "/to"},
{"/a", "/b"},
{"/aa", ""},
{"/", ""},
{"/a?foo=bar", "/b"},
{"/asdf?foo=bar", ""},
{"/foo#bar", ""},
{"/a#foo", "/b"},
} {
var nextCalled bool
re := Redirect{
Next: middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
nextCalled = true
return 0, nil
}),
Rules: []Rule{
{From: "/from", To: "/to"},
{From: "/a", To: "/b"},
},
}
req, err := http.NewRequest("GET", test.from, nil)
if err != nil {
t.Fatalf("Test %d: Could not create HTTP request: %v", i, err)
}
rec := httptest.NewRecorder()
re.ServeHTTP(rec, req)
if rec.Header().Get("Location") != test.expectedLocation {
t.Errorf("Test %d: Expected Location header to be %q but was %q",
i, test.expectedLocation, rec.Header().Get("Location"))
}
if nextCalled && test.expectedLocation != "" {
t.Errorf("Test %d: Next handler was unexpectedly called", i)
}
}
}
示例11: TestRealIP
func TestRealIP(t *testing.T) {
for i, test := range []struct {
actualIP string
headerVal string
expectedIP string
}{
{"1.2.3.4:123", "", "1.2.3.4:123"},
{"4.4.255.255:123", "", "4.4.255.255:123"},
{"4.5.0.0:123", "1.2.3.4", "1.2.3.4:123"},
{"4.5.2.3:123", "1.2.6.7,5.6.7.8,111.111.111.111", "1.2.6.7:123"},
{"4.5.5.5:123", "NOTANIP", "4.5.5.5:123"},
{"aaaaaa", "1.2.3.4", "aaaaaa"},
{"aaaaaa:123", "1.2.3.4", "aaaaaa:123"},
} {
remoteAddr := ""
_, ipnet, err := net.ParseCIDR("4.5.0.0/16") // "4.5.x.x"
if err != nil {
t.Fatal(err)
}
he := &module{
next: middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
remoteAddr = r.RemoteAddr
return 0, nil
}),
Header: "X-Real-IP",
From: []*net.IPNet{ipnet},
}
req, err := http.NewRequest("GET", "http://foo.tld/", nil)
if err != nil {
t.Fatalf("Test %d: Could not create HTTP request: %v", i, err)
}
req.RemoteAddr = test.actualIP
if test.headerVal != "" {
req.Header.Set("X-Real-IP", test.headerVal)
}
rec := httptest.NewRecorder()
he.ServeHTTP(rec, req)
if remoteAddr != test.expectedIP {
t.Errorf("Test %d: Expected '%s', but found '%s'", i, test.expectedIP, remoteAddr)
}
}
}
示例12: TestExtensions
func TestExtensions(t *testing.T) {
rootDir := os.TempDir()
// create a temporary page
path := filepath.Join(rootDir, "extensions_test.html")
_, err := os.Create(path)
if err != nil {
t.Fatal(err)
}
defer os.Remove(path)
for i, test := range []struct {
path string
extensions []string
expectedURL string
}{
{"/extensions_test", []string{".html"}, "/extensions_test.html"},
{"/extensions_test/", []string{".html"}, "/extensions_test/"},
{"/extensions_test", []string{".json"}, "/extensions_test"},
{"/another_test", []string{".html"}, "/another_test"},
{"", []string{".html"}, ""},
} {
ex := Ext{
Next: middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
return 0, nil
}),
Root: rootDir,
Extensions: test.extensions,
}
req, err := http.NewRequest("GET", test.path, nil)
if err != nil {
t.Fatalf("Test %d: Could not create HTTP request: %v", i, err)
}
rec := httptest.NewRecorder()
ex.ServeHTTP(rec, req)
if got := req.URL.String(); got != test.expectedURL {
t.Fatalf("Test %d: Got unexpected request URL: %q, wanted %q", i, got, test.expectedURL)
}
}
}
示例13: TestMultipleOverlappingRules
func TestMultipleOverlappingRules(t *testing.T) {
rw := BasicAuth{
Next: middleware.HandlerFunc(contentHandler),
Rules: []Rule{
{Username: "t", Password: PlainMatcher("p1"), Resources: []string{"/t"}},
{Username: "t1", Password: PlainMatcher("p2"), Resources: []string{"/t/t"}},
},
}
tests := []struct {
from string
result int
cred string
}{
{"/t", http.StatusOK, "t:p1"},
{"/t/t", http.StatusOK, "t:p1"},
{"/t/t", http.StatusOK, "t1:p2"},
{"/a", http.StatusOK, "t1:p2"},
{"/t/t", http.StatusUnauthorized, "t1:p3"},
{"/t", http.StatusUnauthorized, "t1:p2"},
}
for i, test := range tests {
req, err := http.NewRequest("GET", test.from, nil)
if err != nil {
t.Fatalf("Test %d: Could not create HTTP request %v", i, err)
}
auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(test.cred))
req.Header.Set("Authorization", auth)
rec := httptest.NewRecorder()
result, err := rw.ServeHTTP(rec, req)
if err != nil {
t.Fatalf("Test %d: Could not ServeHTTP %v", i, err)
}
if result != test.result {
t.Errorf("Test %d: Expected Header '%d' but was '%d'",
i, test.result, result)
}
}
}
示例14: nextFunc
func nextFunc(shouldGzip bool) middleware.Handler {
return middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
// write a relatively large text file
b, err := ioutil.ReadFile("testdata/test.txt")
if err != nil {
return 500, err
}
if _, err := w.Write(b); err != nil {
return 500, err
}
if shouldGzip {
if r.Header.Get("Accept-Encoding") != "" {
return 0, fmt.Errorf("Accept-Encoding header not expected")
}
if w.Header().Get("Content-Encoding") != "gzip" {
return 0, fmt.Errorf("Content-Encoding must be gzip, found %v", r.Header.Get("Content-Encoding"))
}
if w.Header().Get("Vary") != "Accept-Encoding" {
return 0, fmt.Errorf("Vary must be Accept-Encoding, found %v", r.Header.Get("Vary"))
}
if _, ok := w.(*gzipResponseWriter); !ok {
return 0, fmt.Errorf("ResponseWriter should be gzipResponseWriter, found %T", w)
}
if strings.Contains(w.Header().Get("Content-Type"), "application/x-gzip") {
return 0, fmt.Errorf("Content type should not be gzip.")
}
return 0, nil
}
if r.Header.Get("Accept-Encoding") == "" {
return 0, fmt.Errorf("Accept-Encoding header expected")
}
if w.Header().Get("Content-Encoding") == "gzip" {
return 0, fmt.Errorf("Content-Encoding must not be gzip, found gzip")
}
if _, ok := w.(*gzipResponseWriter); ok {
return 0, fmt.Errorf("ResponseWriter should not be gzipResponseWriter")
}
return 0, nil
})
}
示例15: TestInternal
func TestInternal(t *testing.T) {
im := Internal{
Next: middleware.HandlerFunc(internalTestHandlerFunc),
Paths: []string{"/internal"},
}
tests := []struct {
url string
expectedCode int
expectedBody string
}{
{"/internal", http.StatusNotFound, ""},
{"/public", 0, "/public"},
{"/public/internal", 0, "/public/internal"},
{"/redirect", 0, "/internal"},
{"/cycle", http.StatusInternalServerError, ""},
}
for i, test := range tests {
req, err := http.NewRequest("GET", test.url, nil)
if err != nil {
t.Fatalf("Test %d: Could not create HTTP request: %v", i, err)
}
rec := httptest.NewRecorder()
code, err := im.ServeHTTP(rec, req)
if code != test.expectedCode {
t.Errorf("Test %d: Expected status code %d for %s, but got %d",
i, test.expectedCode, test.url, code)
}
if rec.Body.String() != test.expectedBody {
t.Errorf("Test %d: Expected body '%s' for %s, but got '%s'",
i, test.expectedBody, test.url, rec.Body.String())
}
}
}