Simple go static file server sample

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Follow up with the study, stay for reference

1, the core is the need to get the absolute path of the file, OS. Open () required;

2, Windows uses "\" to indicate the path, and go needs "/" to represent the path, so you need to replace "\" with "/";

3, use the built-in HTTP. The Serverfile () function provides subsequent file transfer services;

Package Mainimport ("FMT" "Log" "Net/http" "OS" "Path/filepath" "strings") var Staticdir = "/static" func Getcurdir () string {dir, err: = FilePath. Abs (filepath. Dir (OS. Args[0])) if err! = Nil {log. Fatal (ERR)}return strings. Replace (dir, "\ \", "/",-1)}func Dealstaticfiles (w http). Responsewriter, R *http. Request) {stdir: = Getcurdir () if strings. Hasprefix (R.url. Path, Staticdir) {file: = Stdir + R.url. Pathfmt.println (file) F, err: = OS. Open (file) defer f.close () if err! = Nil && os. Isnotexist (Err) {FMT. Fprintln (W, "File not Exist") return}http. Servefile (W, R, file) return} else {fmt. Fprintln (W, "Hello World")}}func Main () {http. Handlefunc ("/", Dealstaticfiles)    //set access to the route err: = http. Listenandserve (": 8080", nil)//Set the listening port if err! = Nil {log. Fatal ("Listenandserve:", Err)}}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.