當前位置: 首頁>>代碼示例>>Golang>>正文


Golang httpserver.HandlerFunc函數代碼示例

本文整理匯總了Golang中github.com/mholt/caddy/caddyhttp/httpserver.HandlerFunc函數的典型用法代碼示例。如果您正苦於以下問題:Golang HandlerFunc函數的具體用法?Golang HandlerFunc怎麽用?Golang HandlerFunc使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了HandlerFunc函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: TestStatus

func TestStatus(t *testing.T) {
	status := Status{
		Rules: []httpserver.HandlerConfig{
			NewRule("/foo", http.StatusNotFound),
			NewRule("/teapot", http.StatusTeapot),
			NewRule("/foo/bar1", http.StatusInternalServerError),
			NewRule("/temporary-redirected", http.StatusTemporaryRedirect),
		},
		Next: httpserver.HandlerFunc(urlPrinter),
	}

	tests := []struct {
		path           string
		statusExpected bool
		status         int
	}{
		{"/foo", true, http.StatusNotFound},
		{"/teapot", true, http.StatusTeapot},
		{"/foo/bar", true, http.StatusNotFound},
		{"/foo/bar1", true, http.StatusInternalServerError},
		{"/someotherpath", false, 0},
		{"/temporary-redirected", false, http.StatusTemporaryRedirect},
	}

	for i, test := range tests {
		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()
		actualStatus, err := status.ServeHTTP(rec, req)
		if err != nil {
			t.Fatalf("Test %d: Serving request failed with error %v",
				i, err)
		}

		if test.statusExpected {
			if test.status != actualStatus {
				t.Errorf("Test %d: Expected status code %d, got %d",
					i, test.status, actualStatus)
			}
			if rec.Body.String() != "" {
				t.Errorf("Test %d: Expected empty body, got '%s'",
					i, rec.Body.String())
			}
		} else {
			if test.status != 0 { // Expecting status in response
				if test.status != rec.Code {
					t.Errorf("Test %d: Expected status code %d, got %d",
						i, test.status, rec.Code)
				}
			} else if rec.Body.String() != test.path {
				t.Errorf("Test %d: Expected body '%s', got '%s'",
					i, test.path, rec.Body.String())
			}
		}
	}
}
開發者ID:joshix,項目名稱:caddy,代碼行數:60,代碼來源:status_test.go

示例2: TestMultipleHeaders

func TestMultipleHeaders(t *testing.T) {
	he := Headers{
		Next: httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
			fmt.Fprint(w, "This is a test")
			return 0, nil
		}),
		Rules: []Rule{
			{Path: "/a", Headers: []Header{
				{Name: "+Link", Value: "</images/image.png>; rel=preload"},
				{Name: "+Link", Value: "</css/main.css>; rel=preload"},
			}},
		},
	}

	req, err := http.NewRequest("GET", "/a", nil)
	if err != nil {
		t.Fatalf("Could not create HTTP request: %v", err)
	}

	rec := httptest.NewRecorder()
	he.ServeHTTP(rec, req)

	desiredHeaders := []string{"</css/main.css>; rel=preload", "</images/image.png>; rel=preload"}
	actualHeaders := rec.HeaderMap[http.CanonicalHeaderKey("Link")]
	sort.Strings(actualHeaders)

	if !reflect.DeepEqual(desiredHeaders, actualHeaders) {
		t.Errorf("Expected header to contain: %v but got: %v", desiredHeaders, actualHeaders)
	}
}
開發者ID:Makpoc,項目名稱:caddy,代碼行數:30,代碼來源:header_test.go

示例3: TestExpVar

func TestExpVar(t *testing.T) {
	rw := ExpVar{
		Next:     httpserver.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)
		}
	}
}
開發者ID:FiloSottile,項目名稱:caddy,代碼行數:30,代碼來源:expvar_test.go

示例4: nextFunc

func nextFunc(ss string) httpserver.Handler {
	return httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
		if _, err := w.Write([]byte(ss)); err != nil {
			return 500, err
		}
		return 200, nil
	})
}
開發者ID:pschlump,項目名稱:caddy-jsonp,代碼行數:8,代碼來源:jsonp_test.go

示例5: 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: httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
			t.Fatalf("Next shouldn't be called")
			return 0, nil
		}),
		Configs: []Config{
			{
				PathScope: "/photos",
				Root:      http.Dir("./testdata"),
				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, _ := 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)
	}

}
開發者ID:FiloSottile,項目名稱:caddy,代碼行數:58,代碼來源:browse_test.go

示例6: TestLogRequestBody

func TestLogRequestBody(t *testing.T) {
	var got bytes.Buffer
	logger := Logger{
		Rules: []*Rule{{
			PathScope: "/",
			Entries: []*Entry{{
				Format: "{request_body}",
				Log:    log.New(&got, "", 0),
			}},
		}},
		Next: httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
			// drain up body
			ioutil.ReadAll(r.Body)
			return 0, nil
		}),
	}

	for i, c := range []struct {
		body   string
		expect string
	}{
		{"", "\n"},
		{"{hello} world!", "{hello} world!\n"},
		{func() string {
			length := httpserver.MaxLogBodySize + 100
			b := make([]byte, length)
			for i := 0; i < length; i++ {
				b[i] = 0xab
			}
			return string(b)
		}(), func() string {
			b := make([]byte, httpserver.MaxLogBodySize)
			for i := 0; i < httpserver.MaxLogBodySize; i++ {
				b[i] = 0xab
			}
			return string(b) + "\n"
		}(),
		},
	} {
		got.Reset()
		r, err := http.NewRequest("POST", "/", bytes.NewBufferString(c.body))
		if err != nil {
			t.Fatal(err)
		}
		r.Header.Set("Content-Type", "application/json")
		status, err := logger.ServeHTTP(httptest.NewRecorder(), r)
		if status != 0 {
			t.Errorf("case %d: Expected status to be 0, but was %d", i, status)
		}
		if err != nil {
			t.Errorf("case %d: Expected error to be nil, instead got: %v", i, err)
		}
		if got.String() != c.expect {
			t.Errorf("case %d: Expected body %q, but got %q", i, c.expect, got.String())
		}
	}
}
開發者ID:FiloSottile,項目名稱:caddy,代碼行數:57,代碼來源:log_test.go

示例7: genErrorHandler

func genErrorHandler(status int, err error, body string) httpserver.Handler {
	return httpserver.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
	})
}
開發者ID:evermax,項目名稱:caddy,代碼行數:9,代碼來源:errors_test.go

示例8: newTestHandler

func newTestHandler(t *testing.T, caddyFile string) *handler {
	c := caddy.NewTestController("http", caddyFile)
	mc, err := parse(c)
	if err != nil {
		t.Fatal(err)
	}
	h := newHandler(mc, nil)
	h.Next = httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
		return http.StatusTeapot, nil
	})
	return h
}
開發者ID:SchumacherFM,項目名稱:mailout,代碼行數:12,代碼來源:serve_test.go

示例9: TestHeader

func TestHeader(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", "Server", ""},
		{"/a", "ServerName", hostname},
		{"/b", "Foo", ""},
		{"/b", "Bar", "Removed in /a"},
	} {
		he := Headers{
			Next: httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
				w.Header().Set("Bar", "Removed in /a")
				w.WriteHeader(http.StatusOK)
				return 0, nil
			}),
			Rules: []Rule{
				{Path: "/a", Headers: http.Header{
					"Foo":        []string{"Bar"},
					"ServerName": []string{"{hostname}"},
					"-Bar":       []string{""},
					"-Server":    []string{},
				}},
			},
		}

		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()
		// preset header
		rec.Header().Set("Server", "Caddy")

		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)
		}
	}
}
開發者ID:ollie314,項目名稱:caddy,代碼行數:51,代碼來源:header_test.go

示例10: TestBasicAuth

func TestBasicAuth(t *testing.T) {
	rw := BasicAuth{
		Next: httpserver.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)
			}
		}

	}

}
開發者ID:evermax,項目名稱:caddy,代碼行數:50,代碼來源:basicauth_test.go

示例11: nextFunc

func nextFunc(shouldMime bool, contentType string) httpserver.Handler {
	return httpserver.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
	})
}
開發者ID:FiloSottile,項目名稱:caddy,代碼行數:14,代碼來源:mime_test.go

示例12: 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 = httpserver.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)
			}
		}
	}
}
開發者ID:FiloSottile,項目名稱:caddy,代碼行數:46,代碼來源:responsefilter_test.go

示例13: TestMultiEntries

func TestMultiEntries(t *testing.T) {
	var (
		got1 bytes.Buffer
		got2 bytes.Buffer
	)
	logger := Logger{
		Rules: []*Rule{{
			PathScope: "/",
			Entries: []*Entry{
				{
					Format: "foo {request_body}",
					Log:    log.New(&got1, "", 0),
				},
				{
					Format: "{method} {request_body}",
					Log:    log.New(&got2, "", 0),
				},
			},
		}},
		Next: httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
			// drain up body
			ioutil.ReadAll(r.Body)
			return 0, nil
		}),
	}

	r, err := http.NewRequest("POST", "/", bytes.NewBufferString("hello world"))
	if err != nil {
		t.Fatal(err)
	}
	r.Header.Set("Content-Type", "application/json")
	status, err := logger.ServeHTTP(httptest.NewRecorder(), r)
	if status != 0 {
		t.Errorf("Expected status to be 0, but was %d", status)
	}
	if err != nil {
		t.Errorf("Expected error to be nil, instead got: %v", err)
	}
	if got, expect := got1.String(), "foo hello world\n"; got != expect {
		t.Errorf("Expected %q, but got %q", expect, got)
	}
	if got, expect := got2.String(), "POST hello world\n"; got != expect {
		t.Errorf("Expected %q, but got %q", expect, got)
	}
}
開發者ID:ollie314,項目名稱:caddy,代碼行數:45,代碼來源:log_test.go

示例14: TestMultipleOverlappingRules

func TestMultipleOverlappingRules(t *testing.T) {
	rw := BasicAuth{
		Next: httpserver.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)
		}

	}

}
開發者ID:evermax,項目名稱:caddy,代碼行數:44,代碼來源:basicauth_test.go

示例15: nextFunc

func nextFunc(shouldGzip bool) httpserver.Handler {
	return httpserver.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
	})
}
開發者ID:FiloSottile,項目名稱:caddy,代碼行數:41,代碼來源:gzip_test.go


注:本文中的github.com/mholt/caddy/caddyhttp/httpserver.HandlerFunc函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。