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


Golang Router.ServeHTTP方法代码示例

本文整理汇总了Golang中github.com/gorilla/mux.Router.ServeHTTP方法的典型用法代码示例。如果您正苦于以下问题:Golang Router.ServeHTTP方法的具体用法?Golang Router.ServeHTTP怎么用?Golang Router.ServeHTTP使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在github.com/gorilla/mux.Router的用法示例。


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

示例1: wrapRouter

// Returns a top-level HTTP handler for a Router. This adds behavior for URLs that don't
// match anything -- it handles the OPTIONS method as well as returning either a 404 or 405
// for URLs that don't match a route.
func wrapRouter(sc *ServerContext, privs handlerPrivs, router *mux.Router) http.Handler {
	return http.HandlerFunc(func(response http.ResponseWriter, rq *http.Request) {
		fixQuotedSlashes(rq)
		var match mux.RouteMatch
		if router.Match(rq, &match) {
			router.ServeHTTP(response, rq)
		} else {
			// Log the request
			h := newHandler(sc, privs, response, rq)
			h.logRequestLine()

			// What methods would have matched?
			var options []string
			for _, method := range []string{"GET", "HEAD", "POST", "PUT", "DELETE"} {
				if wouldMatch(router, rq, method) {
					options = append(options, method)
				}
			}
			if len(options) == 0 {
				h.writeStatus(http.StatusNotFound, "unknown URL")
			} else {
				response.Header().Add("Allow", strings.Join(options, ", "))
				if rq.Method != "OPTIONS" {
					h.writeStatus(http.StatusMethodNotAllowed, "")
				}
			}
		}
	})
}
开发者ID:jnordberg,项目名称:sync_gateway,代码行数:32,代码来源:routing.go

示例2: TestErrorExpectedResponse

// TestErrorExpectedResponse is the generic test code for testing for a bad response
func TestErrorExpectedResponse(t *testing.T, router *mux.Router, method, url, route string, data io.Reader, accessToken, msg string, code int, assertExpectations func()) {
	// Prepare a request
	r, err := http.NewRequest(
		method,
		url,
		data,
	)
	assert.NoError(t, err)

	// Optionally add a bearer token to headers
	if accessToken != "" {
		r.Header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken))
	}

	// Check the routing
	match := new(mux.RouteMatch)
	router.Match(r, match)
	if assert.NotNil(t, match.Route) {
		assert.Equal(t, route, match.Route.GetName())
	}

	// And serve the request
	w := httptest.NewRecorder()
	router.ServeHTTP(w, r)

	TestResponseForError(t, w, msg, code)

	assertExpectations()
}
开发者ID:RichardKnop,项目名称:example-api,代码行数:30,代码来源:helpers.go

示例3: IssueRequest

// IssueTestRequest executes an HTTP request described by rt, to a
// specified REST router.  It returns the HTTP response to the request.
func IssueRequest(router *mux.Router, rt *RequestTester) *httptest.ResponseRecorder {
	response := httptest.NewRecorder()
	body := bytes.NewReader(rt.request_body)
	req, _ := http.NewRequest(rt.method, rt.uri, body)
	if rt.api_token != "" {
		req.Header.Set("Authorization", "OAuth2 "+rt.api_token)
	}
	router.ServeHTTP(response, req)
	return response
}
开发者ID:ntijanic,项目名称:arvados,代码行数:12,代码来源:handler_test.go

示例4: getRoles

func getRoles(router *mux.Router, recorder *httptest.ResponseRecorder, request *http.Request) []string {
	var roles []string
	router.ServeHTTP(recorder, request)
	Expect(recorder.Code).To(Equal(200))

	body, err := ioutil.ReadAll(io.LimitReader(recorder.Body, bufferLength))
	Expect(err).To(BeNil())

	err = json.Unmarshal(body, &roles)
	Expect(err).To(BeNil())

	return roles
}
开发者ID:livenson,项目名称:fox,代码行数:13,代码来源:login_test.go

示例5: MakeRequest

func MakeRequest(method, urlStr string, body io.Reader, router *mux.Router) *httptest.ResponseRecorder {
	req, err := http.NewRequest(method, urlStr, body)

	if err != nil {
		fmt.Println(err)
	}

	w := httptest.NewRecorder()

	router.ServeHTTP(w, req)

	return w
}
开发者ID:efrenfuentes,项目名称:go-authentication,代码行数:13,代码来源:test.go

示例6: sampleRequest

func sampleRequest(router *mux.Router,
	method string, urlPath string, body []byte) []byte {
	req := &http.Request{
		Method: method,
		URL:    &url.URL{Path: urlPath},
		Form:   url.Values(nil),
		Body:   ioutil.NopCloser(bytes.NewBuffer(body)),
	}
	record := httptest.NewRecorder()
	router.ServeHTTP(record, req)
	if record.Code != 200 {
		return nil
	}
	return record.Body.Bytes()
}
开发者ID:WillGardella,项目名称:cbft,代码行数:15,代码来源:main.go

示例7: TestErrorExpectedResponse

// TestErrorExpectedResponse is the generic test code for testing for a bad response
func TestErrorExpectedResponse(t *testing.T, router *mux.Router, operation, url, msg string, code int, data io.Reader) {
	// Prepare a request
	r, err := http.NewRequest(
		operation,
		url,
		data,
	)
	assert.NoError(t, err)

	// Mock authentication
	r.Header.Set("Authorization", "Bearer test_token")

	// And serve the request
	w := httptest.NewRecorder()
	router.ServeHTTP(w, r)
	TestResponseForError(t, w, msg, code)
}
开发者ID:RichardKnop,项目名称:example-api,代码行数:18,代码来源:test_helper.go

示例8: wrapRouter

// Returns a top-level HTTP handler for a Router. This adds behavior for URLs that don't
// match anything -- it handles the OPTIONS method as well as returning either a 404 or 405
// for URLs that don't match a route.
func wrapRouter(sc *ServerContext, privs handlerPrivs, router *mux.Router) http.Handler {
	return http.HandlerFunc(func(response http.ResponseWriter, rq *http.Request) {
		fixQuotedSlashes(rq)
		var match mux.RouteMatch

		// Inject CORS if enabled and requested and not admin port
		originHeader := rq.Header["Origin"]
		if privs != adminPrivs && sc.config.CORS != nil && len(originHeader) > 0 {
			origin := matchedOrigin(sc.config.CORS.Origin, originHeader)
			response.Header().Add("Access-Control-Allow-Origin", origin)
			response.Header().Add("Access-Control-Allow-Credentials", "true")
			response.Header().Add("Access-Control-Allow-Headers", strings.Join(sc.config.CORS.Headers, ", "))
		}

		if router.Match(rq, &match) {
			router.ServeHTTP(response, rq)
		} else {
			// Log the request
			h := newHandler(sc, privs, response, rq, false)
			h.logRequestLine()

			// What methods would have matched?
			var options []string
			for _, method := range []string{"GET", "HEAD", "POST", "PUT", "DELETE"} {
				if wouldMatch(router, rq, method) {
					options = append(options, method)
				}
			}
			if len(options) == 0 {
				h.writeStatus(http.StatusNotFound, "unknown URL")
			} else {
				response.Header().Add("Allow", strings.Join(options, ", "))
				if privs != adminPrivs && sc.config.CORS != nil && len(originHeader) > 0 {
					response.Header().Add("Access-Control-Max-Age", strconv.Itoa(sc.config.CORS.MaxAge))
					response.Header().Add("Access-Control-Allow-Methods", strings.Join(options, ", "))
				}
				if rq.Method != "OPTIONS" {
					h.writeStatus(http.StatusMethodNotAllowed, "")
				} else {
					h.writeStatus(http.StatusNoContent, "")
				}
			}
			h.logDuration(true)
		}
	})
}
开发者ID:joeljeske,项目名称:sync_gateway,代码行数:49,代码来源:routing.go

示例9: getFox

func getFox(uuid string, router *mux.Router) Fox {
	var r *http.Request
	var f *Fox

	recorder := httptest.NewRecorder()
	r, _ = http.NewRequest("GET", "/fox/foxes/"+uuid, nil)
	router.ServeHTTP(recorder, r)
	Expect(recorder.Code).To(Equal(200))

	body, err := ioutil.ReadAll(io.LimitReader(recorder.Body, bufferLength))
	Expect(err).To(BeNil())

	f = new(Fox)

	err = json.Unmarshal(body, f)
	Expect(err).To(BeNil())

	return *f
}
开发者ID:mkasep,项目名称:fox,代码行数:19,代码来源:fox_test.go

示例10: wrapRouter

// Returns a top-level HTTP handler for a Router. This adds behavior for URLs that don't
// match anything -- it handles the OPTIONS method as well as returning either a 404 or 405
// for URLs that don't match a route.
func wrapRouter(sc *ServerContext, privs handlerPrivs, router *mux.Router) http.Handler {
	return http.HandlerFunc(func(response http.ResponseWriter, rq *http.Request) {
		fixQuotedSlashes(rq)
		var match mux.RouteMatch

		//if sc.config.CORS != nil {
		response.Header().Add("Access-Control-Allow-Origin", "*")
		response.Header().Add("Access-Control-Allow-Credentials", "true")
		response.Header().Add("Access-Control-Allow-Headers", "DNT, X-Mx-ReqToken, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type")
		// }

		if router.Match(rq, &match) {
			router.ServeHTTP(response, rq)
		} else {
			// Log the request
			h := newHandler(sc, privs, response, rq)
			h.logRequestLine()

			// What methods would have matched?
			var options []string
			for _, method := range []string{"GET", "HEAD", "POST", "PUT", "DELETE"} {
				if wouldMatch(router, rq, method) {
					options = append(options, method)
				}
			}
			if len(options) == 0 {
				h.writeStatus(http.StatusNotFound, "unknown URL")
			} else {
				response.Header().Add("Allow", strings.Join(options, ", "))
				//if sc.config.CORS != nil {
				response.Header().Add("Access-Control-Max-Age", "1728000")
				response.Header().Add("Access-Control-Allow-Methods", strings.Join(options, ", "))
				// }
				if rq.Method != "OPTIONS" {
					h.writeStatus(http.StatusMethodNotAllowed, "")
				}
			}
		}
	})
}
开发者ID:TPWeb,项目名称:sync_gateway,代码行数:43,代码来源:routing.go

示例11: TopologyHandler

// TopologyHandler registers the various topology routes with a http mux.
//
// The returned http.Handler has to be passed directly to http.ListenAndServe,
// and cannot be nested inside another gorrilla.mux.
//
// Routes which should be matched before the topology routes should be added
// to a router and passed in preRoutes.  Routes to be matches after topology
// routes should be added to a router and passed to postRoutes.
func TopologyHandler(c Reporter, preRoutes *mux.Router, postRoutes http.Handler) http.Handler {
	get := preRoutes.Methods("GET").Subrouter()
	get.HandleFunc("/api", gzipHandler(apiHandler))
	get.HandleFunc("/api/topology", gzipHandler(topologyRegistry.makeTopologyList(c)))
	get.HandleFunc("/api/topology/{topology}",
		gzipHandler(topologyRegistry.captureRenderer(c, handleTopology)))
	get.HandleFunc("/api/topology/{topology}/ws",
		topologyRegistry.captureRenderer(c, handleWs)) // NB not gzip!
	get.HandleFunc("/api/report", gzipHandler(makeRawReportHandler(c)))

	// We pull in the http.DefaultServeMux to get the pprof routes
	preRoutes.PathPrefix("/debug/pprof").Handler(http.DefaultServeMux)

	if postRoutes != nil {
		preRoutes.PathPrefix("/").Handler(postRoutes)
	}

	// We have to handle the node details path manually due to
	// various bugs in gorilla.mux and Go URL parsing.  See #804.
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		vars, match := matchURL(r, "/api/topology/{topology}/{id}")
		if !match {
			preRoutes.ServeHTTP(w, r)
			return
		}

		topologyID := vars["topology"]
		nodeID := vars["id"]
		if nodeID == "ws" {
			preRoutes.ServeHTTP(w, r)
			return
		}

		handler := gzipHandler(topologyRegistry.captureRendererWithoutFilters(
			c, topologyID, handleNode(nodeID),
		))
		handler.ServeHTTP(w, r)
	})
}
开发者ID:rnd-ua,项目名称:scope,代码行数:47,代码来源:router.go

示例12: testRESTHandlers

func testRESTHandlers(t *testing.T,
	tests []*RESTHandlerTest, router *mux.Router) {
	for _, test := range tests {
		if test.Before != nil {
			test.Before()
		}
		if test.Method != "NOOP" {
			req := &http.Request{
				Method: test.Method,
				URL:    &url.URL{Path: test.Path},
				Form:   test.Params,
				Body:   ioutil.NopCloser(bytes.NewBuffer(test.Body)),
			}
			record := httptest.NewRecorder()
			router.ServeHTTP(record, req)
			test.check(t, record)
		}
		if test.After != nil {
			test.After()
		}
	}
}
开发者ID:steveyen,项目名称:cbgt,代码行数:22,代码来源:rest_test.go

示例13: addFox

func addFox(f Fox, router *mux.Router) string {
	var id *UUID
	var r *http.Request

	m, _ := json.Marshal(f)

	recorder := httptest.NewRecorder()
	r, _ = http.NewRequest("POST", "/fox/foxes", bytes.NewReader(m))

	router.ServeHTTP(recorder, r)
	Expect(recorder.Code).To(Equal(201))

	body, err := ioutil.ReadAll(io.LimitReader(recorder.Body, bufferLength))
	Expect(err).To(BeNil())

	id = new(UUID)

	err = json.Unmarshal(body, id)
	Expect(err).To(BeNil())

	return id.Uuid
}
开发者ID:mkasep,项目名称:fox,代码行数:22,代码来源:fox_test.go

示例14: routerHandlerFunc

func routerHandlerFunc(router *mux.Router) http.HandlerFunc {
	return func(res http.ResponseWriter, req *http.Request) {
		router.ServeHTTP(res, req)
	}
}
开发者ID:Robin3D,项目名称:gobyexample,代码行数:5,代码来源:server.go

示例15:

		chocStorage := storage.NewChocolateStorage()
		api.AddResource(model.User{}, resource.UserResource{ChocStorage: chocStorage, UserStorage: userStorage})
		api.AddResource(model.Chocolate{}, resource.ChocolateResource{ChocStorage: chocStorage, UserStorage: userStorage})
	})

	BeforeEach(func() {
		log.SetOutput(ioutil.Discard)
		rec = httptest.NewRecorder()
	})

	Context("CRUD Tests", func() {
		It("will create a new user", func() {
			reqBody := strings.NewReader(`{"data": [{"attributes": {"username": "Sansa Stark"}, "id": "1", "type": "users"}]}`)
			req, err := http.NewRequest("POST", "/api/users", reqBody)
			Expect(err).To(BeNil())
			r.ServeHTTP(rec, req)
			Expect(rec.Code).To(Equal(http.StatusCreated))
		})

		It("will find her", func() {
			expectedUser := `
			{
				"data":
				{
					"attributes":{
						"user-name":"Sansa Stark"
					},
					"id":"1",
					"relationships":{
						"sweets":{
							"data":[],"links":{"related":"/api/users/1/sweets","self":"/api/users/1/relationships/sweets"}
开发者ID:pegli,项目名称:api2go-adapter,代码行数:31,代码来源:gorillamux_test.go


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