小编Hau*_* Ma的帖子

HTTP 静态文件处理程序不断显示目录列表

当我实现静态服务器处理程序时,如果我访问根路径,它将显示整个目录,如下所示:

访问根文件夹

我的代码是:

package main

import (
    "flag"
    "log"
    "net/http"
    "strings"
)

func main() {
    port := flag.String("p", "3000", "port to serve on")
    directory := flag.String("d", ".", "the directory of static file to host")
    flag.Parse()

    http.Handle("/statics/", http.StripPrefix(strings.TrimRight("/statics/", "/"), http.FileServer(http.Dir(*directory))))

    log.Printf("Serving %s on HTTP port: %s\n", *directory, *port)
    log.Fatal(http.ListenAndServe(":"+*port, nil))
}
Run Code Online (Sandbox Code Playgroud)

转到:http://locahost:3000/statics/

http static-files go

4
推荐指数
1
解决办法
1068
查看次数

如何将os.Stdout输出复制到字符串变量

我有这样的功能:

package main

import (
    "fmt"
)

// PrintSomething prints some thing
func PrintSomething() {
    fmt.Println("print something")
}

func main() {
    PrintSomething()
}
Run Code Online (Sandbox Code Playgroud)

如何将PrintSomething包装到另一个函数调用CaptureSomething以将字符串"print something"保存到变量并返回它?

go output

1
推荐指数
1
解决办法
917
查看次数

在 Go 中使用相同的 *os.File 写入和读取文件

我想写一些东西到一个文件然后从同一个 *os.File 指针读取它们。但什么都没有读

package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
)

func main() {
    filename := "test.txt"
    f, _ := os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_RDWR, os.ModePerm)
    defer os.Remove(filename)
    // write 10 times
    for i := 0; i < 10; i++ {
        fmt.Fprintf(f, "test%d\n", i)
    }
    // read 10 times
    r := bufio.NewReader(f)
    for i := 0; i < 10; i++ {
        str, _, err := r.ReadLine()
        if err != nil {
            if err == io.EOF {
                fmt.Println("Done")
                return
            }
            fmt.Println("Error", err)
        } …
Run Code Online (Sandbox Code Playgroud)

file go

1
推荐指数
1
解决办法
128
查看次数

标签 统计

go ×3

file ×1

http ×1

output ×1

static-files ×1