100 line GOLNG code write a static file server

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

Always talk about Golang standard library, not only people look bored, I write their own are more uncomfortable, so write a simple static file server, there is upload download, and simple HTML, you can according to your own needs to modify ~ ~

Include Features

    1. Static file Templates
    2. File Upload
    3. File View and download

The packages used

import (    "fmt"    "html/template"    "io"    "net/http"    "os"    "path/filepath"    "regexp"    "strconv"    "time")

Include Knowledge points

//静态文件服务器http.FileServer(http.Dir("目录"))//手工配置服务和路由s := &http.Server{    Addr:           ":8080",    Handler:        myHandler,    ReadTimeout:    10 * time.Second,    WriteTimeout:   10 * time.Second,    MaxHeaderBytes: 1 << 20,}s.ListenAndServe();// path/filepath包的使用

Very little, but there are a lot of basics to play with friends who learn Golang, code example address: Http://github.com/widuu/staticserver

Instance Code staticserver.go

Package Mainimport ("FMT" "html/template" "io" "net/http" "OS" "Path/filepath" "RegExp" "StrConv" "Time") var mux map[string]func (http. Responsewriter, *http. Request) type MyHandler struct{}type home struct {Title string}const (template_dir = "./view/" Upload_dir = ". /upload/") Func main () {server: = http. server{Addr: ": 9090", Handler: &myhandler{}, Readtimeout:10 * time. Second,} MUX = Make (Map[string]func (HTTP. Responsewriter, *http. Request)) mux["/"] = Index mux["/upload"] = upload mux["/file"] = Staticserver server. Listenandserve ()}func (*myhandler) servehttp (w http. Responsewriter, R *http. Request) {if h, OK: = Mux[r.url. String ()]; OK {h (W, R) return} If OK, _: = RegExp. Matchstring ("/css/", R.url. String ()); OK {http. Stripprefix ("/css/", http. Fileserver (http. Dir ("./css/"))). Servehttp (W, R)} else {http. Stripprefix ("/", HTTP. Fileserver (http. Dir ("./upload/")). Servehttp (W, R)}}func upload (w http. Responsewriter, R *http. Request) {if R.method = = "GET" {T, _: = template.         Parsefiles (Template_dir + "file.html") T.execute (w, "Upload file")} else {r.parsemultipartform (<< 20) File, handler, err: = R.formfile ("UploadFile") if err! = Nil {fmt. fprintf (W, "%v", "Upload Error") return} Fileext: = FilePath. EXT (handler. Filename) if check (fileext) = = False {fmt. fprintf (W, "%v", "Disallowed upload type") return} filename: = StrConv. Formatint (time. Now (). Unix (), ten) + Fileext F, _: = OS. OpenFile (Upload_dir+filename, OS. O_create|os. O_wronly, 0660) _, err = Io. Copy (f, file) if err! = Nil {fmt. fprintf (W, "%v", "Upload Failed") return} Filedir, _: = FilePath. Abs (upload_dir + filename) fmt. fprintf (W, "%v", filename+ "upload complete, server address:" +filedir)}}func Index (w http. Responsewriter, R *http. REquest) {title: = Home{title: "Home"} t, _: = template. Parsefiles (Template_dir + "index.html") T.execute (W, title)}func Staticserver (w http. Responsewriter, R *http. Request) {http. Stripprefix ("/file", http. Fileserver (http. Dir ("./upload/"))).        Servehttp (W, R)}func check (name string) BOOL {ext: = []string{". exe", ". js", ". png"} for _, V: = Range Ext { If v = = name {return False}} return true}

Do not reprint any article of this station without permission: Micro Network» 100 lines golng Code write a static file server

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.