當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。