Golang文件服务器Demo

Golang luoluolzb 浏览548次
package main

import (
    "fmt"
    "io"
    "net/http"
    "os"
    "runtime"
    "strings"
    "time"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // 控制台打印请求信息
        fmt.Printf("[%s][%s] %s %s\n",
            time.Now().Format("2006/01/02 15:04:05"),
            r.RemoteAddr,
            r.Method,
            r.URL.Path)

        // 添加HTTP头 Server: go1.16.2
        w.Header().Set("Server", runtime.Version())

        // 获取要求的文件路径
        path := "./html" + r.URL.Path
        // 如果是目录则访问 index.html 文件
        if strings.HasSuffix(path, "/") {
            path += "index.html"
        }

        // 读取要请求的文件内容
        bytes, err := os.ReadFile(path)

        // 处理错误
        if err != nil {
            // 控制台显示错误信息
            fmt.Println("Error:", err)

            if os.IsNotExist(err) {
                w.WriteHeader(http.StatusNotFound)
                io.WriteString(w, "404 Not Found")
            } else if os.IsPermission(err) {
                w.WriteHeader(http.StatusForbidden)
                io.WriteString(w, "403 Forbidden")
            } else {
                w.WriteHeader(http.StatusInternalServerError)
                io.WriteString(w, "500 Internal Server Error")
            }
            return
        }

        // 发送文件内容
        w.Write(bytes)
    })

    // 监听8080端口
    http.ListenAndServe(":8080", nil)
}

本文标签: Golang

版权声明:本文为作者原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.luoluolzb.cn/articles/105/golang-file-server-demo
您需要登录后才发布评论。 点此登录
用户评论 (0条)

暂无评论,赶紧发表一下你的看法吧。