Skip to content
Permalink
Browse files

add 3 minute timeout to load and serve snippets

Snippets are expected to be small and should be relatively quick
to fetch and serve. Add a 3 minute timeout as a sanity check.
  • Loading branch information...
dmitshur committed Jun 24, 2019
1 parent 7d16d03 commit eb3ae24c517a8af4f4b6bc048848930bc26afc39
Showing with 10 additions and 3 deletions.
  1. +7 −1 main.go
  2. +3 −2 store.go
@@ -8,12 +8,14 @@
package main

import (
"context"
"flag"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"time"

"golang.org/x/net/webdav"
)
@@ -114,7 +116,11 @@ func (s *Server) PHandler(w http.ResponseWriter, req *http.Request) {
return
}

snippet, err := s.Store.LoadSnippet(req.Context(), id)
// Set a 3 minute timeout to load and serve the snippet.
ctx, cancel := context.WithTimeout(req.Context(), 3*time.Minute)
defer cancel()

snippet, err := s.Store.LoadSnippet(ctx, id)
if os.IsNotExist(err) {
// Snippet not found.
http.Error(w, "Snippet not found.", http.StatusNotFound)
@@ -59,12 +59,13 @@ func (s *Store) LoadSnippet(ctx context.Context, id string) (io.ReadCloser, erro
// It returns an error that satisfies os.IsNotExist if snippet is not found.
// If it returns nil error, the ReadCloser must be closed by caller.
func fetchSnippetFromGoPlayground(ctx context.Context, id string) (io.ReadCloser, error) {
req, err := http.NewRequest("GET", "https://play.golang.org/p/"+id+".go", nil)
req, err := http.NewRequest(http.MethodGet, "https://play.golang.org/p/"+id+".go", nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
req.Header.Set("User-Agent", userAgent)
resp, err := http.DefaultClient.Do(req.WithContext(ctx))
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}

0 comments on commit eb3ae24

Please sign in to comment.
You can’t perform that action at this time.