前后端分离的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服务器》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

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

Rationality for Mortals

Rationality for Mortals

Gerd Gigerenzer / Oxford University Press, USA / 2008-05-02 / USD 65.00

Gerd Gigerenzer's influential work examines the rationality of individuals not from the perspective of logic or probability, but from the point of view of adaptation to the real world of human behavio......一起来看看 《Rationality for Mortals》 这本书的介绍吧!

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

UNIX 时间戳转换

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具