V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
YYYMagic

请教彦祖,如何根据用户请求 URI 返回不同的文件内容呢

  •  
  •   YYYMagic ·
    binc4t · Oct 26, 2021 · 3041 views
    This topic created in 1646 days ago, the information mentioned may be changed or developed.
    假如本地有一份文件 data.txt ,内容为
    name, Hello!

    正常情况是用户来请求这份文件,我调用 http.ServeFile 即可。
    但是如果想在不改变本地文件内容的前提下,根据不同用户请求 uri 来替换 name ,然后再返回给不同的用户,请问该如何实现呢?
    难道要重写 http.ServeFile 吗
    11 replies    2021-10-26 23:15:56 +08:00
    Aresrun
        1
    Aresrun  
       Oct 26, 2021
    文件名作为路由参数?如 127.0.0.1:8080/file/:fileName ?
    libook
        2
    libook  
       Oct 26, 2021
    按照 HTTP 标准来说的话,请求 URL 是什么,最终下载的文件名就是什么,比如客户端请求的是 data1.txt ,你给他传 data.txt 的内容,用户下载的时候浏览器会根据 URL 默认文件名为 data1.txt 。
    除此之外可以配置一个 Content-Disposition 头来让浏览器忽略 URL 中的文件名,使用这个头字段值里包含的信息作为文件名,具体可以去看 MDN 。

    框架提供的静态文件 serve 功能如果不支持将 data1.txt 映射成 data.txt 的话,可能就得你自己指定路径读文件内容,然后 respond 给客户端。
    xiao109
        3
    xiao109  
       Oct 26, 2021
    用模板嘛。data.txt 是模板,根据不同用户的 name 去填充然后生成真正的文件保存再返回给客户。
    IvanLi127
        4
    IvanLi127  
       Oct 26, 2021 via Android
    这不就是模板渲染引擎的工作嘛!
    cmdOptionKana
        5
    cmdOptionKana  
       Oct 26, 2021
    简单来说,不存在一个固定的 data.txt ,要么事先准备好一堆不同的 txt ,要么每次请求时才生成一个特定的 txt 。
    Trim21
        6
    Trim21  
       Oct 26, 2021 via Android
    是用户的浏览器下载这个文件吗?只要设置好对应 header ,浏览器就会选择下载文件而不是直接显示内容了。
    然后再把你期望的文件内容作为这个请求的 body 就行了。
    Trim21
        7
    Trim21  
       Oct 26, 2021 via Android
    @Trim21 作为这个响应的 body
    br_wang
        8
    br_wang  
       Oct 26, 2021
    @xiao109 对的。类似发送系统邮件。
    ch2
        9
    ch2  
       Oct 26, 2021
    Response.AppendHeader("Content-Disposition","attachment;filename=FileName.txt");
    响应体传你定义后的文件内容
    leoleoasd
        10
    leoleoasd  
       Oct 26, 2021
    YYYMagic
        11
    YYYMagic  
    OP
       Oct 26, 2021
    谢谢大家的意见啦!!!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1610 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 64ms · UTC 16:33 · PVG 00:33 · LAX 09:33 · JFK 12:33
    ♥ Do have faith in what you're doing.