前后端分离的Golang静态web服务器|反向代理Api请求

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请求)