首页 > 其他分享 >Go - Serving Static Files

Go - Serving Static Files

时间:2023-10-17 19:55:50浏览次数:25  
标签:Files FileServer use Serving http static file Go Dir

Problem: You want to serve static files such as images, CSS, and JavaScript files.


Solution: Use the http.FileServer function to serve static files.

 

func   main ()   { 
      dir   :=   http . Dir ( "./static" ) 
      fs   :=   http . FileServer ( dir ) 
      http . Handle ( "/" ,   fs ) 
      http . ListenAndServe ( ":8000" ,   nil ) 
}

First, you need to understand where you want to serve the files from. For this, use http.Dir . Despite how it looks, http.Dir is not a function but a type. It’s a type that implements the http.FileSystem interface so the first line typecasts the directory such that it becomes a http.Dir . 

Next, the http.FileServer function takes in the http.Dir as a parameter and returns an http.Handler that can be used to serve the files. 

Finally, call the http.Handle function to register the http.Handler as the handler for the / URL pattern. 

The previous information broke down the steps, but most of the time, you’ll use it this way:

func   main ()   { 
      http . Handle ( "/" ,   http . FileServer ( http . Dir ( "./static" ))) 
      http . ListenAndServe ( ":8000" ,   nil ) 
}

                  

This works because you use / as the URL to start from. However, once you start using different ones, you’ll need to use http.StripPrefix to remove the prefix:

func   main ()   { 
      dir   :=   http . Dir ( "./static" ) 
      fs   :=   http . FileServer ( dir ) 
      fs   =   http . StripPrefix ( "/static" ,   fs ) 
      http . Handle ( "/static/" ,   fs ) 
      http . ListenAndServe ( ":8000" ,   nil ) 
}

               

The main difference comes when you want to use /static as the root URL (or any other starting point). If you proceed as before, when the user requests for a file /static/rfc2616.txt , the file server you look for a file called /static/static/rfc2616.txt . To avoid this, use the http.StripPrefix function to remove the prefix /static from the request URL before it is passed to the file server. As before, you normally do it all in a single line:

func   main ()   { 
      http . Handle ( "/static/" ,   http . StripPrefix ( "/static" ,  http . FileServer ( http . Dir ( "./static" )))) 
      http . ListenAndServe ( ":8000" ,   nil ) 
}

This seems quite redundant, but actually there is another reason for this. In the example, you have a directory called static , and you want to serve it out from the /static URL. You could have a directory called datafiles , for example, but you want the user to access it from the /static URL:

func   main ()   { 
      http . Handle ( "/static/" ,   http . StripPrefix ( "/static" ,  http . FileServer ( http . Dir ( "./datafiles" )))) 
      http . ListenAndServe ( ":8000" ,   nil ) 
}

                    

You should be aware that http.FileServer will list all the contents of the directory that it is serving. This is might not be a major problem if you don’t care if the user can see the contents of the directory.

However, if you want to prevent this, you can create and place an index.html file in the directory. This file will be served instead of the directory listing. index.html can be anything, including being empty; it just needs to be there.

If you want to serve a single file, just use http.ServeFile :

func   main ()   { 
      file   :=   func ( w   http . ResponseWriter ,   r   * http . Request )   { 
          http . ServeFile ( w ,   r ,   "./static/a.txt" ) 
      } 
      http . HandleFunc ( "/static/a" ,   file ) 
      http . ListenAndServe ( ":8000" ,   nil ) 
}

               

The http.ServeFile function takes in an http.ResponseWriter , an http.Request , and the path to the file you want to serve. If you wrap it around an anonymous function, you can use it as a handler function, which we did in the example.

 

标签:Files,FileServer,use,Serving,http,static,file,Go,Dir
From: https://www.cnblogs.com/zhangzhihui/p/17770513.html

相关文章

  • RunnerGo UI自动化使用体验
    RunnerGo怎么做UI自动化首先需要进入官网,RunnerGo支持开源,可以自行下载安装,也可以点击右上角体验企业版按钮快速体验 点击体验企业版进入工作台后可以点击页面上方的UI自动化进入到测试页面 创建元素我们可以在元素管理中创建我们测试时需要的元素 这里我们以一个......
  • 用go封装和实现扫码登录
    用go封装和实现扫码登录本篇为用go设计开发一个自己的轻量级登录库/框架吧-秋玻-博客园(cnblogs.com)的扫码登录业务篇,会讲讲扫码登录的实现,给库/框架增加新的功能,最后说明使用方法Github:https://github.com/weloe/token-go扫码登录流程首先我们需要知道扫码登录流程打......
  • Django必会三板斧
    HttpResponse=========返回字符串类型的数据render      ==========返回html页面并且支持传值redirect  =========重定向 使用方法:fromdjango.shortcutsimportrender,HttpResponse,redirectdefindex(request):""":paramrequest:请......
  • 解决TypeError: read_excel() got an unexpected keyword argument ‘parse_cols or
    解决TypeError:read_excel()gotanunexpectedkeywordargument‘parse_cols'或‘sheetname‘在使用pandas包进行Excel文件处理时,有时候会遇到TypeError:read_excel()gotanunexpectedkeywordargument‘parse_cols'或TypeError:read_excel()gotanunexpectedkeyword......
  • 使用docker搭建drogon windows10,linux,mac下开发环境
    2023年10月13日14:52:26本机环境Windows10专业版22H2操作内核19045.2965如果直接在windows,linux,mac上直接搭建环境确实有一点难度,之前drogon官方并未提供官方镜像,现在有了docker镜像确实方便了,其实我是最近才有简述安装dockerdesktop,windows的虚拟化有2个方案hyper-v和w......
  • 【转】,接上面3篇.Implement Sql Database Driver in 100 Lines of Go
    原文: https://vyskocil.org/blog/implement-sql-database-driver-in-100-lines-of-go/ -------------------- ImplementSqlDatabaseDriverin100LinesofGo2019.02.18Go database/sql definesinterfacesforSQLdatabases.Actualdrivermustbeimplemented......
  • 【转】dive into golang database/sql(1)
    转,原文:https://www.jianshu.com/p/3b0b3a4c83da ---------------数据库操作是一个应用必不可少的部分,但是我们很多时候对golang的sql包仅仅是会用,这是不够的。每一条语句的执行,它的背后到底发生了什么。各式各样对sql包的封装,是不是有必要的,有没有做无用功?这是gotodataba......
  • 【转】dive into golang database/sql(3)
    转,原文: https://www.jianshu.com/p/cd8cee3d7fc3 ----------------上一章中我们一起探讨了golangdatabase/sql包中如何获取一个真实的数据库连接。当我们拿到一个数据库连接之后就可以开始真正的数据库操作了。本章讲继续深入,一起探讨底层是如何进行数据库操作的。上一章......
  • 【转】dive into golang database/sql(2)
    转,原文: https://www.jianshu.com/p/807257fcb985?utm_campaign=studygolang.com&utm_medium=studygolang.com&utm_source=studygolang.com ----------当我们拿到一个DB实例之后就可以操作数据库了。本篇我们将更加深入database/sql包,共同探讨连接池的维护和请求的处理。上......
  • 线上mongo慢查询可能原因影响
    mongo主从节点影响python中pymongo库的MongoClient类中readPreference参数可选主从(primary,secondary),不指定默认为主节点线上部署的时候其实是有指定主从节点的连接类,但是后期开发在基类中从节点的方法逐渐被替代,导致后期的业务的查询压力来到了主节点......