package staticServer
import (
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"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 strings.HasPrefix(r.URL.Path, "/api") || strings.HasPrefix(r.URL.Path, "/upload") {
remote, _ := url.Parse("http://127.0.0.1:8888")
r.URL.Path = strings.TrimPrefix(r.URL.Path, "/api")
proxy := httputil.NewSingleHostReverseProxy(remote)
proxy.ServeHTTP(w, r)
return
}
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服务器|反向代理Api请求
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 1. 为什么需要 “前后端分离、web与static服务器分离” web前端的发展历史大致可以分为两个阶段:nod...
- 前后端分离、web与static服务器分离 1. 为什么需要 “前后端分离、web与static服务器分离” we...