zoukankan      html  css  js  c++  java
  • net/http中 StripPrefix 详解(go 文件服务器搭建)

    首先我们看下标准库文档中定义以及解释

    func StripPrefix(prefix string, h Handler) Handler
    

    StripPrefix返回一个处理器,该处理器会将请求的URL.Path字段中给定前缀prefix去除后再交由h处理。StripPrefix会向URL.Path字段中没有给定前缀的请求回复404 page not found。

    // 官方提供的demo
    // To serve a directory on disk (/tmp) under an alternate URL
    // 在备用URL下在磁盘(/tmp)上提供目录 
    // path (/tmpfiles/), use StripPrefix to modify the request
    // 路径(/tmpfiles/),使用StripPrefix修改请求
    // URL's path before the FileServer sees it:
    // 文件服务器看到它之前的URL路径:
    http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
    

    翻译过来的参数签名是这样的

    http.Handle("url/Prefix", http.StripPrefix("/Prefix", http.FileServer(http.Dir("/now"))))
    // 等于是访问到的url/now路径
    

    同时 Go很轻易就可以搭建一个文件服务器

    http.Handle("/", http.StripPrefix("/file", http.FileServer(http.Dir("./static"))))
    // 访问 127.0.0.1:8888/file/hello -> hello world
    // 文件目录
    // - main.go
    // - static
    // -/- hello
    http.ListenAndServe(":8888", nil)
    
    Songzhibin
  • 相关阅读:
    bash while until 循环用法
    微信小程序入门介绍
    jquery遍历
    jquery获取元素和DOM获取元素
    ul在div中水平居中效果
    一个文字在一个图片上水平居中,并且悬浮变大特效
    一个div在另一个div中垂直居中的方法
    layer插件的使用
    百度分享插件使用
    图标字体
  • 原文地址:https://www.cnblogs.com/binHome/p/13914506.html
Copyright © 2011-2022 走看看