duan198727 2017-12-10 23:36
浏览 51

Go Server不断提供过时的文件[重复]

This question already has an answer here:

I'm using Go to build a website. When serving in static files, css and js, no matter what I do the updates to files will not show. I've tried cache busting, deleting cache in my web browser, and deleting the disk cache on my computer, but no matter what ( even across different browsers ) an old version of the file is served. I've looked all over an found no answers.

To illustrate, I have a file main.css

html {
    text-align:center;
}

However, the following css ( from an older file ) shows up in browser

html {
    background-color:red;
}

Chrome's Developer Tools saying the css is loading in with a status of 200.

My Questions:

1) What is going on?

2) How do I fix this issue?

My code is as follows: test.go package main

import (
    "html/template"
    "log"
    "net/http"
)

type PageVariables struct {
    Name         string
}

func main() {
    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
    http.HandleFunc("/", HomePage)
    log.Fatal(http.ListenAndServe(":8000", nil))
}

func HomePage(w http.ResponseWriter, r *http.Request){
    HomePageVars := PageVariables{ //store the date and time in a struct
      Name: "PDiddy",
    }
    t, err := template.ParseFiles("homepage.html") //parse the html file homepage.html
    if err != nil { // if there is an error
      log.Print("template parsing error: ", err) // log it
    }
    err = t.Execute(w, HomePageVars) //execute the template and pass it the HomePageVars struct to fill in the gaps
    if err != nil { // if there is an error
      log.Print("template executing error: ", err) //log it
    }
}

homepage.html

<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="./static/css/main.css">
</head>
<body>
  <div class="container-fluid">
  <div class="jumbotron">
    <div class="row">
      <h1>Welcome to HQ {{.Name}}</h1>
      <div class="col-sm-4">
          <h2>Here's Whats Happening</h2>
      </div>
      <div class="col-sm-8">
          <h2>Select A Company</h2>
      </div>
    </div>
  </div>
</div>
</body>
</html>
</div>
  • 写回答

1条回答 默认 最新

  • dssj88098 2017-12-11 14:03
    关注

    Well, I'm create package with full copy of you code. All work well (add screenshot). enter image description here

    May be you need check package structure? My tree response.

    .
    ├── homepage.html
    ├── static
    │   └── css
    │       └── main.css
    └── test.go
    
    2 directories, 3 files
    

    Also I write unit-tests for you case. Please replace this lines to func init() in you test.go (for set handlers in http.DefaultServeMux)

     func init() {
        http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
        http.HandleFunc("/", HomePage)
     }
    

    test_test.go this code compare equality static/css/main.css and http://localhost:8000/static/css/main.css.

    package main
    
    import (
        "fmt"
        "io/ioutil"
        "net/http"
        "net/http/httptest"
        "testing"
    )
    
    func test(no int, name, addr, filepath string) error {
        var (
            err        error
            body, data []byte
            resp       *http.Response
    
            fmtError = func(step string, err error) error {
                return fmt.Errorf("Test #%d: error in testing <%s> in '%s' method
        %s", no, step, name, err)
            }
        )
    
        if resp, err = http.Get(addr); err != nil {
            return fmtError(fmt.Sprintf("HTTP GET %s", addr), err)
        } else if no == 0 {
            return nil
        }
    
        if data, err = ioutil.ReadFile(filepath); err != nil {
            return fmtError("read file", err)
        }
    
        if body, err = ioutil.ReadAll(resp.Body); err != nil {
            return fmtError("read response data", err)
        } else if string(body) != string(data) {
            return fmtError("compare data", fmt.Errorf("File data and response body not equal"))
        } else if err = resp.Body.Close(); err != nil {
            return fmtError("HTTP response body close", err)
        }
    
        return nil
    }
    
    func TestServer(t *testing.T) {
        var (
            ts = httptest.NewServer(http.DefaultServeMux)
    
            testData = []struct {
                Name, Addr, File string
            }{
                {
                    Name: "Index",
                    Addr: "/",
                    File: "homepage.html",
                },
                {
                    Name: "main.css",
                    Addr: "/static/css/main.css",
                    File: "static/css/main.css",
                },
            }
        )
        defer ts.Close()
    
        for i, tt := range testData {
            if err := test(i, tt.Name, ts.URL+tt.Addr, tt.File); err != nil {
                t.Fatal(err)
            }
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建