# 环境 Linux dan 4.15.0-91-generic #92-Ubuntu SMP Fri Feb 28 11:09:48 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
## ./main.go
```go
package main
import (
"fmt"
"net/http"
)
func home(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("<h1>地址为: " + r.URL.Path + " 你好,世界!</h1>"))
//fmt.Printf("来访者: Method:%v Path:%v Scheme:%v \n", r.Method, r.URL.Path, r.URL.Scheme)
}
func show(w http.ResponseWriter, r *http.Request) {
imgPath := getRandPath("/root/tp8")
http.ServeFile(w, r, imgPath)
}
func main() {
http.HandleFunc("/home", home)
http.HandleFunc("/p", show)
fmt.Println("服务器开启成功! http://localhost/home")
err := http.ListenAndServe(":80", nil)
if err != nil {
panic(err)
}
}
```
## ./t.go
```go
package main
import (
"fmt"
"net/http"
)
func home(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("<h1>地址为: " + r.URL.Path + " 你好,世界!</h1>"))
//fmt.Printf("来访者: Method:%v Path:%v Scheme:%v \n", r.Method, r.URL.Path, r.URL.Scheme)
}
func show(w http.ResponseWriter, r *http.Request) {
imgPath := getRandPath("/root/tp8")
http.ServeFile(w, r, imgPath)
}
func main() {
http.HandleFunc("/home", home)
http.HandleFunc("/p", show)
fmt.Println("服务器开启成功! http://localhost/home")
err := http.ListenAndServe(":80", nil)
if err != nil {
panic(err)
}
}
root@dan:~/gocode/src/8niWang# cat t.go
package main
import (
"io/ioutil"
"log"
"math/rand"
"time"
)
func ReadAllDir(path string) {
//path = strings.Replace(path, "/", "\\", -1)
FileInfo, err := ioutil.ReadDir(path)
if err != nil {
log.Fatalln("读取文件夹出错")
}
// 多协程遍历目录
for _, fileInfo := range FileInfo {
if fileInfo.IsDir() {
ReadAllDir(path + "/" + fileInfo.Name())
} else {
savePath(path + "/" + fileInfo.Name())
}
}
return
}
// 保存文件地址
var sPath []string
var AA int
func savePath(path string) {
sPath = append(sPath, path)
return
}
// 从文件切片里随机取一个文件地址
func getRandPath(path string) string {
ReadAllDir(path)
arrLen := len(sPath)
rand.Seed(time.Now().Unix())
r := rand.New(rand.NewSource(time.Now().UnixNano()))
return sPath[r.Intn(arrLen)]
}
//func main(){
// path := getRandPath("/root/tp8")
// log.Println(path)
//}
```
# 报错: go build main.go
# command-line-arguments
./main.go:13:13: undefined: getRandPath
有疑问加站长微信联系(非本文作者)