Skip to content

Commit

Permalink
Merge pull request #10 from pepabo/fix_status_code
Browse files Browse the repository at this point in the history
オリジンが404を返した場合はクライアントにも404を返すようにする
  • Loading branch information
ryuichi1208 authored Nov 28, 2023
2 parents 8a5d5cb + 7018485 commit c36396f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 10 deletions.
17 changes: 7 additions & 10 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,19 +83,16 @@ func proxy(w http.ResponseWriter, r *http.Request) {
pathExt := filepath.Ext(req.URL.Path)
if pathExt == ".webp" {
orgRes, err = doWebp(req)
if err != nil {
http.Error(w, "Get origin failed", http.StatusBadGateway)
log.Printf("Get origin failed. %v\n", err)
return
}
} else {
orgRes, err = client.Do(req)
if err != nil {
http.Error(w, "Get origin failed", http.StatusBadGateway)
log.Printf("Get origin failed. %v\n", err)
return
}
}

if err != nil || orgRes.StatusCode == http.StatusNotFound {
http.Error(w, "Get origin failed", orgRes.StatusCode)
log.Printf("Get origin failed. %v\n", err)
return
}

defer orgRes.Body.Close()
if orgRes.Header.Get("Last-Modified") != "" {
w.Header().Set("Last-Modified", orgRes.Header.Get("Last-Modified"))
Expand Down
21 changes: 21 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,27 @@ func TestOriginNotExist(t *testing.T) {
t.Fatal(err)
}

if res.StatusCode != http.StatusNotFound {
t.Errorf("HTTP status is %d, want %d", res.StatusCode, http.StatusNotFound)
}
}

func TestOriginBadGateWay(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(proxy))

origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "502 Bad Gateway", http.StatusBadGateway)
}))

orgSrvURL = origin.URL

url := ts.URL + "/bad.jpg"

res, err := http.Get(url)
if err != nil {
t.Fatal(err)
}

if res.StatusCode != http.StatusBadGateway {
t.Errorf("HTTP status is %d, want %d", res.StatusCode, http.StatusBadGateway)
}
Expand Down

0 comments on commit c36396f

Please sign in to comment.