前后端分离的Golang静态web服务器

栏目: Go · 发布时间: 7年前

package staticServer

import (
    "fmt"
    "net/http"
    "os"
    "time"
)

const staticPath = "./web" // 静态web目录

func Start() {
    serveMux := http.NewServeMux()
    serveMux.HandleFunc("/", StaticServer)
    server := http.Server{
        Addr:        ":8080",
        Handler:     serveMux,
        ReadTimeout: 10 * time.Second,
    }
    err := server.ListenAndServe()
    if err != nil {
        fmt.Println(err)
    }
}

func StaticServer(w http.ResponseWriter, r *http.Request) {
    if isFile(staticPath + r.URL.Path) {
        http.StripPrefix("/", http.FileServer(http.Dir(staticPath))).ServeHTTP(w, r)
    } else {
        http.StripPrefix(r.URL.Path, http.FileServer(http.Dir(staticPath))).ServeHTTP(w, r)
    }
}

// 是否是文件 不是文件也不一定是目录
func isFile(path string) bool {
    s, err := os.Stat(path)
    if err != nil {
        return false
    }
    return !s.IsDir()
}

以上所述就是小编给大家介绍的《前后端分离的Golang静态web服务器》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

零基础学算法

零基础学算法

戴艳 / 机械工业出版社 / 2009-1 / 59.80元

零基础学算法,ISBN:9787111284048,作者:戴艳 等编著一起来看看 《零基础学算法》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换