当前位置: 首页>>代码示例>>Golang>>正文


Golang http.HandlerFunc函数代码示例

本文整理汇总了Golang中net/http.HandlerFunc函数的典型用法代码示例。如果您正苦于以下问题:Golang HandlerFunc函数的具体用法?Golang HandlerFunc怎么用?Golang HandlerFunc使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了HandlerFunc函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: TestAuthenticateRequest

func TestAuthenticateRequest(t *testing.T) {
	success := make(chan struct{})
	contextMapper := api.NewRequestContextMapper()
	auth, err := NewRequestAuthenticator(
		contextMapper,
		authenticator.RequestFunc(func(req *http.Request) (user.Info, bool, error) {
			return &user.DefaultInfo{Name: "user"}, true, nil
		}),
		http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
			t.Errorf("unexpected call to failed")
		}),
		http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) {
			ctx, ok := contextMapper.Get(req)
			if ctx == nil || !ok {
				t.Errorf("no context stored on contextMapper: %#v", contextMapper)
			}
			user, ok := api.UserFrom(ctx)
			if user == nil || !ok {
				t.Errorf("no user stored in context: %#v", ctx)
			}
			close(success)
		}),
	)

	auth.ServeHTTP(httptest.NewRecorder(), &http.Request{})

	<-success
	empty, err := api.IsEmpty(contextMapper)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if !empty {
		t.Fatalf("contextMapper should have no stored requests: %v", contextMapper)
	}
}
开发者ID:qingyuancloud,项目名称:qingyuan,代码行数:35,代码来源:handlers_test.go

示例2: TestCommitContainer

func TestCommitContainer(t *testing.T) {
	var called bool
	server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "container not found", http.StatusNotFound)
	}))
	defer server1.Close()
	server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		called = true
		w.Write([]byte(`{"Id":"596069db4bf5"}`))
	}))
	defer server2.Close()
	cluster, err := New(nil,
		Node{ID: "handler0", Address: server1.URL},
		Node{ID: "handler1", Address: server2.URL},
	)
	if err != nil {
		t.Fatal(err)
	}
	opts := dclient.CommitContainerOptions{
		Container: "abcdef",
	}
	image, err := cluster.CommitContainer(opts)
	if err != nil {
		t.Fatal(err)
	}
	if image.ID != "596069db4bf5" {
		t.Errorf("CommitContainer: the image container is %s, expected: '596069db4bf5'", image.ID)
	}
	if !called {
		t.Error("CommitContainer: Did not call the remote HTTP API")
	}
}
开发者ID:rainsongsky,项目名称:docker-cluster,代码行数:32,代码来源:container_test.go

示例3: TestNilBody

// Issue 12344
func TestNilBody(t *testing.T) {
	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hi"))
	}))
	defer backend.Close()

	frontend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		backURL, _ := url.Parse(backend.URL)
		rp := NewSingleHostReverseProxy(backURL)
		r := req(t, "GET / HTTP/1.0\r\n\r\n")
		r.Body = nil // this accidentally worked in Go 1.4 and below, so keep it working
		rp.ServeHTTP(w, r)
	}))
	defer frontend.Close()

	res, err := http.Get(frontend.URL)
	if err != nil {
		t.Fatal(err)
	}
	defer res.Body.Close()
	slurp, err := ioutil.ReadAll(res.Body)
	if err != nil {
		t.Fatal(err)
	}
	if string(slurp) != "hi" {
		t.Errorf("Got %q; want %q", slurp, "hi")
	}
}
开发者ID:gmwu,项目名称:go,代码行数:29,代码来源:reverseproxy_test.go

示例4: TestWaitContainerNotFound

func TestWaitContainerNotFound(t *testing.T) {
	server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "No such container", http.StatusNotFound)
	}))
	defer server1.Close()
	server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "No such container", http.StatusNotFound)
	}))
	defer server2.Close()
	cluster, err := New(nil,
		Node{ID: "handler0", Address: server1.URL},
		Node{ID: "handler1", Address: server2.URL},
	)
	if err != nil {
		t.Fatal(err)
	}
	id := "abc123"
	expected := -1
	status, err := cluster.WaitContainer(id)
	if err == nil {
		t.Errorf("WaitContainer(%q): unexpected <nil> error", id)
	}
	if status != expected {
		t.Errorf("WaitContainer(%q): Wrong status. Want %d. Got %d.", id, expected, status)
	}
}
开发者ID:rainsongsky,项目名称:docker-cluster,代码行数:26,代码来源:container_test.go

示例5: TestAttachToContainer

func TestAttachToContainer(t *testing.T) {
	var called bool
	server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "container not found", http.StatusNotFound)
	}))
	defer server1.Close()
	server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		called = true
		w.Write([]byte("something happened"))
	}))
	defer server2.Close()
	cluster, err := New(nil,
		Node{ID: "handler0", Address: server1.URL},
		Node{ID: "handler1", Address: server2.URL},
	)
	if err != nil {
		t.Fatal(err)
	}
	opts := dclient.AttachToContainerOptions{
		Container:    "abcdef",
		OutputStream: &safe.Buffer{},
		Logs:         true,
		Stdout:       true,
	}
	err = cluster.AttachToContainer(opts)
	if err != nil {
		t.Errorf("AttachToContainer: unexpected error. Want <nil>. Got %#v.", err)
	}
	if !called {
		t.Error("AttachToContainer: Did not call the remote HTTP API")
	}
}
开发者ID:rainsongsky,项目名称:docker-cluster,代码行数:32,代码来源:container_test.go

示例6: TestCreateContainer

func TestCreateContainer(t *testing.T) {
	body := `{"Id":"e90302"}`
	handler := []bool{false, false}
	server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		handler[0] = true
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte(body))
	}))
	defer server1.Close()
	server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		handler[1] = true
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte(body))
	}))
	defer server2.Close()
	cluster, err := New(nil,
		Node{ID: "handler0", Address: server1.URL},
		Node{ID: "handler1", Address: server2.URL},
	)
	if err != nil {
		t.Fatal(err)
	}
	config := docker.Config{Memory: 67108864}
	nodeID, container, err := cluster.CreateContainer(&config)
	if err != nil {
		t.Fatal(err)
	}
	if nodeID != "handler0" {
		t.Errorf("CreateContainer: wrong node  ID. Want %q. Got %q.", "handler0", nodeID)
	}
	if container.ID != "e90302" {
		t.Errorf("CreateContainer: wrong container ID. Want %q. Got %q.", "e90302", container.ID)
	}
}
开发者ID:rainsongsky,项目名称:docker-cluster,代码行数:34,代码来源:container_test.go

示例7: TestRestartContainerWithStorage

func TestRestartContainerWithStorage(t *testing.T) {
	var called bool
	server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		called = true
		http.Error(w, "No such container", http.StatusNotFound)
	}))
	defer server1.Close()
	server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("ok"))
	}))
	defer server2.Close()
	cluster, err := New(nil,
		Node{ID: "handler0", Address: server1.URL},
		Node{ID: "handler1", Address: server2.URL},
	)
	if err != nil {
		t.Fatal(err)
	}
	id := "abc123"
	storage := mapStorage{cMap: map[string]string{id: "handler1"}}
	cluster.SetStorage(&storage)
	err = cluster.RestartContainer(id, 10)
	if err != nil {
		t.Fatal(err)
	}
	if called {
		t.Errorf("RestartContainer(%q): should not call the node server", id)
	}
}
开发者ID:rainsongsky,项目名称:docker-cluster,代码行数:29,代码来源:container_test.go

示例8: TestCotacao

func TestCotacao(t *testing.T) {

	Convey("Ao executar o comando cotação", t, func() {
		cmd := &bot.Cmd{}

		Convey("Deve responder com a cotação do dólar e euro", func() {
			ts := httptest.NewServer(
				http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
					fmt.Fprintln(w, expectedJSON)
				}))
			defer ts.Close()

			url = ts.URL

			c, err := cotacao(cmd)

			So(err, ShouldBeNil)
			So(c, ShouldEqual, "Dólar: 2.2430 (+0.36), Euro: 2.9018 (-1.21)")
		})

		Convey("Quando o webservice retornar algo inválido deve retornar erro", func() {
			ts := httptest.NewServer(
				http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
					fmt.Fprintln(w, "invalid")
				}))
			defer ts.Close()

			url = ts.URL

			_, err := cotacao(cmd)

			So(err, ShouldNotBeNil)
		})
	})
}
开发者ID:imtranQ,项目名称:BjornBot,代码行数:35,代码来源:cotacao_test.go

示例9: main

func main() {

	rand.Seed(time.Now().Unix())

	var port string
	if len(os.Args) < 2 {
		port = "80"
	} else {
		port = os.Args[1]
	}
	log.Printf("Port number to listen on = %s\n", port)
	http.Handle("/status/", http.HandlerFunc(status.Status))
	http.Handle("/logon", http.HandlerFunc(config.CloudLogon))
	http.Handle("/getMachine", http.HandlerFunc(config.GetMachineAccount))
	http.Handle("/connect", http.HandlerFunc(config.Connect))
	http.Handle("/dmcConfig", http.HandlerFunc(config.DmcConfig))
	http.Handle("/getBearerForMachine", http.HandlerFunc(config.GetBearerForMachine))
	http.Handle("/getRealToken", http.HandlerFunc(config.GetRealToken))

	//debug related items - intended to aid in standalone, test environment
	http.Handle("/config/", http.HandlerFunc(config.Config))
	http.Handle("/logmeon", http.HandlerFunc(config.LogMeOn))
	http.Handle("/token", http.HandlerFunc(config.Token))
	chan1 := make(chan bool)
	go httpListener(port, chan1)
	go httpTlsListener(chan1)
	select {
	case <-chan1:
		log.Printf("\n\nDetected context done\n\n")
	}
	log.Printf("goodbye\n")
}
开发者ID:mikechack,项目名称:wsrouter,代码行数:32,代码来源:dmcagent.go

示例10: layerDispatcher

// layerDispatcher uses the request context to build a layerHandler.
func layerDispatcher(ctx *Context, r *http.Request) http.Handler {
	dgst, err := getDigest(ctx)
	if err != nil {

		if err == errDigestNotAvailable {
			return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				w.WriteHeader(http.StatusNotFound)
				ctx.Errors.Push(v2.ErrorCodeDigestInvalid, err)
			})
		}

		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			ctx.Errors.Push(v2.ErrorCodeDigestInvalid, err)
		})
	}

	layerHandler := &layerHandler{
		Context: ctx,
		Digest:  dgst,
	}

	return handlers.MethodHandler{
		"GET":  http.HandlerFunc(layerHandler.GetLayer),
		"HEAD": http.HandlerFunc(layerHandler.GetLayer),
	}
}
开发者ID:jhadvig,项目名称:origin,代码行数:27,代码来源:layer.go

示例11: TestBuilder

func TestBuilder(t *testing.T) {
	rv := ""

	builder := &Builder{}
	builder.UseHandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		rv += "a"
	})
	builder.Use(func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			rv += "b"
			next.ServeHTTP(w, r)
			rv += "c"
		})
	})
	builder.UseHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		rv += "X"
	}))
	builder.UseHandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		rv += "d"
	})

	recorder := httptest.NewRecorder()
	builder.ServeHTTP(recorder, (*http.Request)(nil))

	expected := "abXdc"
	if rv != expected {
		t.Errorf("have %q want %q", rv, expected)
	}
}
开发者ID:pnelson,项目名称:waitress,代码行数:29,代码来源:builder_test.go

示例12: TestRedirectPolicyFunc

// TODO: more tests on redirect
func TestRedirectPolicyFunc(t *testing.T) {
	redirectSuccess := false
	redirectFuncGetCalled := false
	tsRedirect := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		redirectSuccess = true
	}))
	defer tsRedirect.Close()
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, tsRedirect.URL, http.StatusMovedPermanently)
	}))
	defer ts.Close()

	New().
		Get(ts.URL).
		RedirectPolicy(func(req Request, via []Request) error {
			redirectFuncGetCalled = true
			return nil
		}).End()
	if !redirectSuccess {
		t.Errorf("Expected reaching another redirect url not original one")
	}
	if !redirectFuncGetCalled {
		t.Errorf("Expected redirect policy func to get called")
	}
}
开发者ID:smallnest,项目名称:goreq,代码行数:26,代码来源:goreq_test.go

示例13: TestPatRoutingMethodNotAllowed

func TestPatRoutingMethodNotAllowed(t *testing.T) {
	p := New()

	var ok bool
	p.Post("/foo/:name", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ok = true
	}))

	p.Put("/foo/:name", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ok = true
	}))

	r := httptest.NewRecorder()
	p.ServeHTTP(r, newRequest("GET", "/foo/keith", nil))

	if ok {
		t.Fatal("handler called when it should have not been allowed")
	}
	if r.Code != http.StatusMethodNotAllowed {
		t.Fatalf("got status %d; expected %d", r.Code, http.StatusMethodNotAllowed)
	}

	got := strings.Split(r.Header().Get("Allow"), ", ")
	sort.Strings(got)
	want := []string{"POST", "PUT"}
	if !reflect.DeepEqual(got, want) {
		t.Fatalf("got Allow header %v; want %v", got, want)
	}
}
开发者ID:nesv,项目名称:pat,代码行数:29,代码来源:mux_test.go

示例14: TestPatImplicitRedirect

func TestPatImplicitRedirect(t *testing.T) {
	p := New()
	p.Get("/foo/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))

	r := newRequest("GET", "/foo", nil)
	res := httptest.NewRecorder()
	p.ServeHTTP(res, r)

	if res.Code != 301 {
		t.Errorf("expected Code 301, was %d", res.Code)
	}

	if loc := res.Header().Get("Location"); loc != "/foo/" {
		t.Errorf("expected %q, got %q", "/foo/", loc)
	}

	p = New()
	p.Get("/foo", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
	p.Get("/foo/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))

	r = newRequest("GET", "/foo", nil)
	res = httptest.NewRecorder()
	res.Code = 200
	p.ServeHTTP(res, r)

	if res.Code != 200 {
		t.Errorf("expected Code 200, was %d", res.Code)
	}
}
开发者ID:nesv,项目名称:pat,代码行数:29,代码来源:mux_test.go

示例15: TestInspectContainer

func TestInspectContainer(t *testing.T) {
	body := `{"Id":"e90302","Path":"date","Args":[]}`
	server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "No such container", http.StatusNotFound)
	}))
	defer server1.Close()
	server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte(body))
	}))
	defer server2.Close()
	server3 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "No such container", http.StatusNotFound)
	}))
	defer server3.Close()
	cluster, err := New(nil,
		Node{ID: "handler0", Address: server1.URL},
		Node{ID: "handler1", Address: server2.URL},
		Node{ID: "handler2", Address: server3.URL},
	)
	if err != nil {
		t.Fatal(err)
	}
	id := "e90302"
	container, err := cluster.InspectContainer(id)
	if err != nil {
		t.Fatal(err)
	}
	if container.ID != id {
		t.Errorf("InspectContainer(%q): Wrong ID. Want %q. Got %q.", id, id, container.ID)
	}
	if container.Path != "date" {
		t.Errorf("InspectContainer(%q): Wrong Path. Want %q. Got %q.", id, "date", container.Path)
	}
}
开发者ID:rainsongsky,项目名称:docker-cluster,代码行数:35,代码来源:container_test.go


注:本文中的net/http.HandlerFunc函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。