本文整理汇总了Golang中net/http.ServeMux.ServeHTTP方法的典型用法代码示例。如果您正苦于以下问题:Golang ServeMux.ServeHTTP方法的具体用法?Golang ServeMux.ServeHTTP怎么用?Golang ServeMux.ServeHTTP使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http.ServeMux
的用法示例。
在下文中一共展示了ServeMux.ServeHTTP方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestHandleFunc
func TestHandleFunc(t *testing.T) {
wfe := setupWFE(t)
var mux *http.ServeMux
var rw *httptest.ResponseRecorder
var stubCalled bool
runWrappedHandler := func(req *http.Request, allowed ...string) {
mux = http.NewServeMux()
rw = httptest.NewRecorder()
stubCalled = false
wfe.HandleFunc(mux, "/test", func(http.ResponseWriter, *http.Request) {
stubCalled = true
}, allowed...)
req.URL = mustParseURL("/test")
mux.ServeHTTP(rw, req)
}
// Plain requests (no CORS)
type testCase struct {
allowed []string
reqMethod string
shouldSucceed bool
}
var lastNonce string
for _, c := range []testCase{
{[]string{"GET", "POST"}, "GET", true},
{[]string{"GET", "POST"}, "POST", true},
{[]string{"GET"}, "", false},
{[]string{"GET"}, "POST", false},
{[]string{"GET"}, "OPTIONS", false}, // TODO, #469
{[]string{"GET"}, "MAKE-COFFEE", false}, // 405, or 418?
} {
runWrappedHandler(&http.Request{Method: c.reqMethod}, c.allowed...)
test.AssertEquals(t, stubCalled, c.shouldSucceed)
if c.shouldSucceed {
test.AssertEquals(t, rw.Code, http.StatusOK)
} else {
test.AssertEquals(t, rw.Code, http.StatusMethodNotAllowed)
test.AssertEquals(t, sortHeader(rw.Header().Get("Allow")), strings.Join(c.allowed, ", "))
test.AssertEquals(t,
rw.Body.String(),
`{"type":"urn:acme:error:malformed","detail":"Method not allowed"}`)
}
nonce := rw.Header().Get("Replay-Nonce")
test.AssertNotEquals(t, nonce, lastNonce)
lastNonce = nonce
}
// Disallowed method returns error JSON in body
runWrappedHandler(&http.Request{Method: "PUT"}, "GET", "POST")
test.AssertEquals(t, rw.Header().Get("Content-Type"), "application/problem+json")
test.AssertEquals(t, rw.Body.String(), `{"type":"urn:acme:error:malformed","detail":"Method not allowed"}`)
test.AssertEquals(t, sortHeader(rw.Header().Get("Allow")), "GET, POST")
// Disallowed method special case: response to HEAD has got no body
runWrappedHandler(&http.Request{Method: "HEAD"}, "GET", "POST")
test.AssertEquals(t, stubCalled, false)
test.AssertEquals(t, rw.Body.String(), "")
test.AssertEquals(t, sortHeader(rw.Header().Get("Allow")), "GET, POST")
}
示例2: Use
func Use(h *http.ServeMux) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
for _, handler := range handlers {
if !handler(w, r) {
// Abort if function responded with false
return
}
}
h.ServeHTTP(w, r)
}
}
示例3: WithProxyMux
func WithProxyMux(handler http.Handler, mux *http.ServeMux) http.Handler {
if mux == nil {
return handler
}
// register the handler at this stage against everything under slash. More specific paths that get registered will take precedence
// this effectively delegates by default unless something specific gets registered.
mux.Handle("/", handler)
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
mux.ServeHTTP(w, req)
})
}
示例4: HandlerMux
func HandlerMux(s *http.ServeMux, rules *rules) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
m := NewMobileDetect(r, rules)
if m.IsTablet() {
context.Set(r, "Device", "Tablet")
} else if m.IsMobile() {
context.Set(r, "Device", "Mobile")
} else {
context.Set(r, "Device", "Desktop")
}
s.ServeHTTP(w, r)
})
}
示例5: setupTChan
func setupTChan(t *testing.T, mux *http.ServeMux) (string, func()) {
ch := testutils.NewServer(t, testutils.NewOpts().SetServiceName("test"))
handler := func(ctx context.Context, call *tchannel.InboundCall) {
req, err := ReadRequest(call)
if !assert.NoError(t, err, "ReadRequest failed") {
return
}
// Make the HTTP call using the default mux.
writer, finish := ResponseWriter(call.Response())
mux.ServeHTTP(writer, req)
finish()
}
ch.Register(tchannel.HandlerFunc(handler), "http")
return ch.PeerInfo().HostPort, func() { ch.Close() }
}
示例6: NewDigestAuthFilter
func NewDigestAuthFilter(myMux *http.ServeMux, tm *JwtManager,
digestRealm string, tlsConfig *tls.Config) http.Handler {
authenticator := auth.NewDigestAuthenticator(digestRealm, func(user, realm string) string {
return getUserString(tlsConfig, user, "digest")
})
newMux := http.NewServeMux()
// Override the builtin wrap function to include our capabilities.
newMux.HandleFunc("/",
authenticator.Wrap(func(w http.ResponseWriter, ar *auth.AuthenticatedRequest) {
t := tm.New(ar.Username)
err := tm.AddTokenInfo(t, w, &ar.Request)
if err != nil {
log.Printf("Add token had issues: %v\n", err)
}
myMux.ServeHTTP(w, &ar.Request)
}))
return newMux
}
示例7: initAdmin
revel.TemplateFuncs["javascript_include_tag"] = train.JavascriptTag
revel.TemplateFuncs["stylesheet_link_tag"] = train.StylesheetTag
}
var AssetsFilter = func(c *revel.Controller, fc []revel.Filter) {
if strings.HasPrefix(c.Request.URL.Path, "/assets") {
train.ServeRequest(c.Response.Out, c.Request.Request)
} else {
fc[0](c, fc[1:])
}
}
var AdminFilter = func(c *revel.Controller, fc []revel.Filter) {
if strings.HasPrefix(c.Request.URL.Path, "/admin") {
mux.ServeHTTP(c.Response.Out, c.Request.Request)
} else {
fc[0](c, fc[1:])
}
}
func initAdmin() {
Admin = admin.New(&qor.Config{DB: models.DB})
Publish = publish.New(models.DB)
sorting.RegisterCallbacks(models.DB)
validations.RegisterCallbacks(models.DB)
nodeSelectMeta := &admin.Meta{Name: "NodeId", Type: "select_one", Collection: nodeCollection}
bodyMeta := &admin.Meta{Name: "Body", Type: "text"}
Admin.AddResource(&admin.AssetManager{}, &admin.Config{Invisible: true})
示例8: RootHandler
func RootHandler(Layout *template.Template, Exits *Exits, domain *gettext.Domain, Phttp *http.ServeMux, Locales map[string]string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// serve public files
if len(r.URL.Path) > 1 {
Phttp.ServeHTTP(w, r)
return
}
var (
err error
isTor bool
host string
onOff string
fingerprint string
)
if host, err = GetHost(r); err == nil {
fingerprint, isTor = Exits.IsTor(host)
}
// short circuit for torbutton
if IsParamSet(r, "TorButton") {
WriteHTMLBuf(w, r, Layout, domain, "torbutton.html", Page{IsTor: isTor})
return
}
// try to determine if it's TBB
notTBB := !LikelyTBB(r.UserAgent())
// users shouldn't be relying on check
// to determine the TBB is up-to-date
// always return false to this param
notUpToDate := IsParamSet(r, "uptodate")
// string used for classes and such
// in the template
if isTor {
if notTBB || notUpToDate {
onOff = "not"
} else {
onOff = "on"
}
} else {
onOff = "off"
}
// instance of your page model
p := Page{
isTor,
notUpToDate,
IsParamSet(r, "small"),
notTBB,
fingerprint,
onOff,
Lang(r),
host,
Locales,
}
// render the template
WriteHTMLBuf(w, r, Layout, domain, "index.html", p)
}
}
示例9: RootHandler
func RootHandler(Layout *template.Template, Exits *Exits, Phttp *http.ServeMux) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
// serve public files
if len(r.URL.Path) > 1 {
Phttp.ServeHTTP(w, r)
return
}
// get remote ip
host := r.Header.Get("X-Forwarded-For")
var err error
if len(host) == 0 {
host, _, err = net.SplitHostPort(r.RemoteAddr)
}
// determine if we're in Tor
var isTor bool
if err != nil {
isTor = false
} else {
isTor = Exits.IsTor(host)
}
// short circuit for torbutton
if len(r.URL.Query().Get("TorButton")) > 0 {
if err := Layout.ExecuteTemplate(w, "torbutton.html", isTor); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
// string used for classes and such
// in the template
var onOff string
if isTor {
onOff = "on"
} else {
onOff = "off"
}
small := Small(r)
upToDate := UpToDate(r)
// querystring params
extra := ""
if small {
extra += "&small=1"
}
if !upToDate {
extra += "&uptodate=0"
}
// instance of your page model
p := Page{
isTor,
isTor && !upToDate,
!small,
onOff,
Lang(r),
host,
extra,
Locales,
}
// render the template
if err := Layout.ExecuteTemplate(w, "index.html", p); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}