dtqysxw4659 2015-08-11 15:24
浏览 6

转到HTTP服务器:使用地图处理路线

I have a map in Go with routes (e.g. /static/stylesheets/main.css) as keys and the corresponding code as the value (effectively, a giant string). I was just wondering, is there an easy way in Go by which I can create an HTTP server, which always check an incoming request against the map and renders the value associated with the matched key, if the key exists?

So far, I have...

func main() {
    var m = generateMap()
    http.handleFunc("/", renderContent);
}

func renderContent(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, m[path]); 
}

I know this code is far from done, but hopefully it clarifies my objective. How would I pass in the path and m into renderContent as well as how do I have handleFunc actually handle regexes (essentially, any path)?

  • 写回答

3条回答 默认 最新

  • dongleiwei2182 2015-08-11 15:35
    关注

    Make your map an http.Handler:

    type httpFiles struct {
        fileMap map[string][]byte
    }
    
    func (hf httpFiles) ServeHTTP(w http.ResponseWriter, r *http.Request) {
        path := r.URL.Path
        w.Write(hf.fileMap[path])
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?