Use FileServer under Golang http package

FileServer document: https://godoc.org/net/http#FileServer

Today saw Handle http method, so as to try to find FileServer

FileServer:

  

           1.www.xx.com/ root path directly

      http.Handle ( "/", http.FileServer (http.Dir ( "/ tmp"))) 

  
     2.www.xx.com/c/ need to add functions of the request path with
      http.Handle("/c/", http.StripPrefix("/c/", http.FileServer(http.Dir("/tmp"))))
package main

import (
        "io"
        "log"
        "net/http"
)

func helloHandler(rw http.ResponseWriter, req *http.Request) {
        url := req.Method + " " + req.URL.Path
        if req.URL.RawQuery != "" {
                url += "?" + req.URL.RawQuery
        }
        log.Println(url)
        io.WriteString(rw, "hello world")
}

func main() {
        http.Handle("/hello", http.NotFoundHandler())
        http.Handle("/dir",http.StripPrefix("/dir", http.FileServer(http.Dir("/usr/local/"))))
        err := http.ListenAndServe(":8080", nil)
        //err := http.ListenAndServe(":8080",http.FileServer(http.Dir("/usr/local/")))
        if err != nil {
                log.Fatal("...")
        }
}

 

Guess you like

Origin blog.csdn.net/Edu_enth/article/details/89519564