本文整理匯總了Golang中github.com/mholt/caddy/caddyhttp/httpserver.Path函數的典型用法代碼示例。如果您正苦於以下問題:Golang Path函數的具體用法?Golang Path怎麽用?Golang Path使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Path函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: ServeHTTP
// ServeHTTP implements the httpserver.Handler interface.
func (i Internal) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
// Internal location requested? -> Not found.
for _, prefix := range i.Paths {
if httpserver.Path(r.URL.Path).Matches(prefix) {
return http.StatusNotFound, nil
}
}
// Use internal response writer to ignore responses that will be
// redirected to internal locations
iw := internalResponseWriter{ResponseWriter: w}
status, err := i.Next.ServeHTTP(iw, r)
for c := 0; c < maxRedirectCount && isInternalRedirect(iw); c++ {
// Redirect - adapt request URL path and send it again
// "down the chain"
r.URL.Path = iw.Header().Get(redirectHeader)
iw.ClearHeader()
status, err = i.Next.ServeHTTP(iw, r)
}
if isInternalRedirect(iw) {
// Too many redirect cycles
iw.ClearHeader()
return http.StatusInternalServerError, nil
}
return status, err
}
示例2: ServeHTTP
// ServeHTTP implements the httpserver.Handler interface and serves requests,
// setting headers on the response according to the configured rules.
func (h Headers) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
replacer := httpserver.NewReplacer(r, nil, "")
rww := &responseWriterWrapper{w: w}
for _, rule := range h.Rules {
if httpserver.Path(r.URL.Path).Matches(rule.Path) {
for name := range rule.Headers {
// One can either delete a header, add multiple values to a header, or simply
// set a header.
if strings.HasPrefix(name, "-") {
rww.delHeader(strings.TrimLeft(name, "-"))
} else if strings.HasPrefix(name, "+") {
for _, value := range rule.Headers[name] {
rww.Header().Add(strings.TrimLeft(name, "+"), replacer.Replace(value))
}
} else {
for _, value := range rule.Headers[name] {
rww.Header().Set(name, replacer.Replace(value))
}
}
}
}
}
return h.Next.ServeHTTP(rww, r)
}
示例3: ServeHTTP
// ServerHTTP is the HTTP handler for this middleware
func (s *Search) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
if httpserver.Path(r.URL.Path).Matches(s.Config.Endpoint) {
if r.Header.Get("Accept") == "application/json" || s.Config.Template == nil {
return s.SearchJSON(w, r)
}
return s.SearchHTML(w, r)
}
record := s.Indexer.Record(r.URL.String())
status, err := s.Next.ServeHTTP(&searchResponseWriter{w, record}, r)
modif := w.Header().Get("Last-Modified")
if len(modif) > 0 {
modTime, err := time.Parse(`Mon, 2 Jan 2006 15:04:05 MST`, modif)
if err == nil {
record.SetModified(modTime)
}
}
if status != http.StatusOK {
record.Ignore()
}
go s.Pipeline.Pipe(record)
return status, err
}
示例4: ServeHTTP
// ServeHTTP handles requests to expvar's configured entry point with
// expvar, or passes all other requests up the chain.
func (e ExpVar) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
if httpserver.Path(r.URL.Path).Matches(string(e.Resource)) {
expvarHandler(w, r)
return 0, nil
}
return e.Next.ServeHTTP(w, r)
}
示例5: ServeHTTP
func (jph JsonPHandlerType) ServeHTTP(www http.ResponseWriter, req *http.Request) (int, error) {
if db1 {
fmt.Printf("JsonPHandlerType.ServeHTTP called\n")
}
for _, prefix := range jph.Paths {
if db1 {
fmt.Printf("Path Matches\n")
}
if httpserver.Path(req.URL.Path).Matches(prefix) {
if db1 {
fmt.Printf("A\n")
}
ResponseBodyRecorder := bufferhtml.NewBufferHTML()
if db1 {
fmt.Printf("B\n")
}
status, err := jph.Next.ServeHTTP(ResponseBodyRecorder, req)
if db1 {
fmt.Printf("C status=%d err=%s\n", status, err)
}
if status == 200 || status == 0 {
// if there is a "callback" argument then use that to format the JSONp response.
if db1 {
fmt.Printf("D Inside, status=%d\n", status)
}
Prefix := ""
Postfix := ""
u, err := url.ParseRequestURI(req.RequestURI)
if err != nil {
ResponseBodyRecorder.FlushAtEnd(www, "", "")
return status, nil
}
m, err := url.ParseQuery(u.RawQuery)
if err != nil {
ResponseBodyRecorder.FlushAtEnd(www, "", "")
return status, nil
}
callback := m.Get("callback")
if callback != "" {
if db1 {
fmt.Printf("Callback = -[%s]-\n", callback)
}
www.Header().Set("Content-Type", "application/javascript")
Prefix = callback + "("
Postfix = ");"
}
ResponseBodyRecorder.FlushAtEnd(www, Prefix, Postfix)
} else {
if db1 {
fmt.Printf("E - error occured, %s\n", err)
}
log.Printf("Error (%s) status %d - from JSONP directive\n", err, status)
}
return status, err
}
}
return jph.Next.ServeHTTP(www, req)
}
示例6: ServeHTTP
// ServeHTTP handles requests to BasePath with pprof, or passes
// all other requests up the chain.
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
if httpserver.Path(r.URL.Path).Matches(BasePath) {
h.Mux.ServeHTTP(w, r)
return 0, nil
}
return h.Next.ServeHTTP(w, r)
}
示例7: Rewrite
// Rewrite rewrites the internal location of the current request.
func (r *ComplexRule) Rewrite(fs http.FileSystem, req *http.Request) (re Result) {
rPath := req.URL.Path
replacer := newReplacer(req)
// validate base
if !httpserver.Path(rPath).Matches(r.Base) {
return
}
// validate extensions
if !r.matchExt(rPath) {
return
}
// validate regexp if present
if r.Regexp != nil {
// include trailing slash in regexp if present
start := len(r.Base)
if strings.HasSuffix(r.Base, "/") {
start--
}
matches := r.FindStringSubmatch(rPath[start:])
switch len(matches) {
case 0:
// no match
return
default:
// set regexp match variables {1}, {2} ...
// url escaped values of ? and #.
q, f := url.QueryEscape("?"), url.QueryEscape("#")
for i := 1; i < len(matches); i++ {
// Special case of unescaped # and ? by stdlib regexp.
// Reverse the unescape.
if strings.ContainsAny(matches[i], "?#") {
matches[i] = strings.NewReplacer("?", q, "#", f).Replace(matches[i])
}
replacer.Set(fmt.Sprint(i), matches[i])
}
}
}
// validate rewrite conditions
for _, i := range r.Ifs {
if !i.True(req) {
return
}
}
// if status is present, stop rewrite and return it.
if r.Status != 0 {
return RewriteStatus
}
// attempt rewrite
return To(fs, req, r.To, replacer)
}
示例8: ServeHTTP
func (l Logger) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
for _, rule := range l.Rules {
if httpserver.Path(r.URL.Path).Matches(rule.PathScope) {
// Record the response
responseRecorder := httpserver.NewResponseRecorder(w)
// Attach the Replacer we'll use so that other middlewares can
// set their own placeholders if they want to.
rep := httpserver.NewReplacer(r, responseRecorder, CommonLogEmptyValue)
responseRecorder.Replacer = rep
// Bon voyage, request!
status, err := l.Next.ServeHTTP(responseRecorder, r)
if status >= 400 {
// There was an error up the chain, but no response has been written yet.
// The error must be handled here so the log entry will record the response size.
if l.ErrorFunc != nil {
l.ErrorFunc(responseRecorder, r, status)
} else {
// Default failover error handler
responseRecorder.WriteHeader(status)
fmt.Fprintf(responseRecorder, "%d %s", status, http.StatusText(status))
}
status = 0
}
// Write log entry
rule.Log.Println(rep.Replace(rule.Format))
return status, err
}
}
return l.Next.ServeHTTP(w, r)
}
示例9: ServeHTTP
// ServeHTTP determines if the request is for this plugin, and if all prerequisites are met.
// If so, control is handed over to ServeListing.
func (b Browse) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
var bc *Config
// See if there's a browse configuration to match the path
for i := range b.Configs {
if httpserver.Path(r.URL.Path).Matches(b.Configs[i].PathScope) {
bc = &b.Configs[i]
goto inScope
}
}
return b.Next.ServeHTTP(w, r)
inScope:
// Browse works on existing directories; delegate everything else
requestedFilepath, err := bc.Root.Open(r.URL.Path)
if err != nil {
switch {
case os.IsPermission(err):
return http.StatusForbidden, err
case os.IsExist(err):
return http.StatusNotFound, err
default:
return b.Next.ServeHTTP(w, r)
}
}
defer requestedFilepath.Close()
info, err := requestedFilepath.Stat()
if err != nil {
switch {
case os.IsPermission(err):
return http.StatusForbidden, err
case os.IsExist(err):
return http.StatusGone, err
default:
return b.Next.ServeHTTP(w, r)
}
}
if !info.IsDir() {
return b.Next.ServeHTTP(w, r)
}
// Do not reply to anything else because it might be nonsensical
switch r.Method {
case http.MethodGet, http.MethodHead:
// proceed, noop
case "PROPFIND", http.MethodOptions:
return http.StatusNotImplemented, nil
default:
return b.Next.ServeHTTP(w, r)
}
// Browsing navigation gets messed up if browsing a directory
// that doesn't end in "/" (which it should, anyway)
if !strings.HasSuffix(r.URL.Path, "/") {
staticfiles.Redirect(w, r, r.URL.Path+"/", http.StatusTemporaryRedirect)
return 0, nil
}
return b.ServeListing(w, r, requestedFilepath, bc)
}
示例10: ShouldAllow
// ShouldAllow takes a path and a request and decides if it should be allowed
func (ipf IPFilter) ShouldAllow(path IPPath, r *http.Request) (bool, string, error) {
allow := true
scopeMatched := ""
// check if we are in one of our scopes.
for _, scope := range path.PathScopes {
if httpserver.Path(r.URL.Path).Matches(scope) {
// extract the client's IP and parse it.
clientIP, err := getClientIP(r, path.Strict)
if err != nil {
return false, scope, err
}
// request status.
var rs Status
if len(path.CountryCodes) != 0 {
// do the lookup.
var result OnlyCountry
if err = ipf.Config.DBHandler.Lookup(clientIP, &result); err != nil {
return false, scope, err
}
// get only the ISOCode out of the lookup results.
clientCountry := result.Country.ISOCode
for _, c := range path.CountryCodes {
if clientCountry == c {
rs.countryMatch = true
break
}
}
}
if len(path.Nets) != 0 {
for _, rng := range path.Nets {
if rng.Contains(clientIP) {
rs.inRange = true
break
}
}
}
scopeMatched = scope
if rs.Any() {
// Rule matched, if the rule has IsBlock = true then we have to deny access
allow = !path.IsBlock
} else {
// Rule did not match, if the rule has IsBlock = true then we have to allow access
allow = path.IsBlock
}
// We only have to test the first path that matches because it is the most specific
break
}
}
// no scope match, pass-through.
return allow, scopeMatched, nil
}
示例11: AllowedPath
func (u *staticUpstream) AllowedPath(requestPath string) bool {
for _, ignoredSubPath := range u.IgnoredSubPaths {
if httpserver.Path(path.Clean(requestPath)).Matches(path.Join(u.From(), ignoredSubPath)) {
return false
}
}
return true
}
示例12: AllowedPath
// AllowedPath checks if requestPath is not an ignored path.
func (r Rule) AllowedPath(requestPath string) bool {
for _, ignoredSubPath := range r.IgnoredSubPaths {
if httpserver.Path(path.Clean(requestPath)).Matches(path.Join(r.Path, ignoredSubPath)) {
return false
}
}
return true
}
示例13: ServeHTTP
// ServeHTTP converts the HTTP request to a WebSocket connection and serves it up.
func (ws WebSocket) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
for _, sockconfig := range ws.Sockets {
if httpserver.Path(r.URL.Path).Matches(sockconfig.Path) {
return serveWS(w, r, &sockconfig)
}
}
// Didn't match a websocket path, so pass-through
return ws.Next.ServeHTTP(w, r)
}
示例14: match
// match finds the best match for a proxy config based
// on r.
func (p Proxy) match(r *http.Request) Upstream {
var u Upstream
var longestMatch int
for _, upstream := range p.Upstreams {
basePath := upstream.From()
if !httpserver.Path(r.URL.Path).Matches(basePath) || !upstream.AllowedPath(r.URL.Path) {
continue
}
if len(basePath) > longestMatch {
longestMatch = len(basePath)
u = upstream
}
}
return u
}
示例15: ServeHTTP
// ServeHTTP implements the httpserver.Handler interface and serves requests,
// setting headers on the response according to the configured rules.
func (h Headers) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
replacer := httpserver.NewReplacer(r, nil, "")
for _, rule := range h.Rules {
if httpserver.Path(r.URL.Path).Matches(rule.Path) {
for _, header := range rule.Headers {
if strings.HasPrefix(header.Name, "-") {
w.Header().Del(strings.TrimLeft(header.Name, "-"))
} else {
w.Header().Set(header.Name, replacer.Replace(header.Value))
}
}
}
}
return h.Next.ServeHTTP(w, r)
}