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

查看所有标签

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

Programming PHP

Programming PHP

Rasmus Lerdorf、Kevin Tatroe、Peter MacIntyre / O'Reilly Media / 2006-5-5 / USD 39.99

Programming PHP, 2nd Edition, is the authoritative guide to PHP 5 and is filled with the unique knowledge of the creator of PHP (Rasmus Lerdorf) and other PHP experts. When it comes to creating websit......一起来看看 《Programming PHP》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具