Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/routes/question.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"anonymousoverflow/config"
"anonymousoverflow/src/scraper"
"anonymousoverflow/src/utils"
"errors"
"fmt"
"os"
"regexp"
Expand Down Expand Up @@ -41,7 +42,11 @@ func ViewQuestion(c *gin.Context) {

newFilteredQuestion, answers, err := questionScraper.GetQuestion(params)
if err != nil {
c.HTML(500, "home.html", gin.H{
status := 500
if errors.Is(err, scraper.ErrQuestionNotFound) {
status = 404
}
c.HTML(status, "home.html", gin.H{
"errorMessage": err,
"version": config.Version,
})
Expand Down
6 changes: 6 additions & 0 deletions src/scraper/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"anonymousoverflow/src/types"
"anonymousoverflow/src/utils"
"encoding/json"
"errors"
"fmt"
"html/template"
"net/http"
Expand Down Expand Up @@ -92,6 +93,8 @@ type ApiScraper struct{ ApiKey string }

const API_URL = "https://api.stackexchange.com/2.3"

var ErrQuestionNotFound = errors.New("Question not found")

func (s ApiScraper) GetQuestion(params ViewQuestionInputs) (types.FilteredQuestion, []types.FilteredAnswer, error) {
client := resty.New()
if s.ApiKey != "" {
Expand Down Expand Up @@ -150,6 +153,9 @@ func getQuestionContent(client *resty.Client, params ViewQuestionInputs) (types.
if err := json.Unmarshal(resp.Body(), &questionsResp); err != nil {
return types.FilteredQuestion{}, err
}
if len(questionsResp.Results) == 0 {
return types.FilteredQuestion{}, ErrQuestionNotFound
}
question := questionsResp.Results[0]

questionBody := template.HTML(utils.ProcessHTMLBody(question.Body))
Expand Down
31 changes: 31 additions & 0 deletions src/scraper/api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package scraper

import (
"errors"
"io"
"net/http"
"strings"
"testing"

"github.com/go-resty/resty/v2"
)

type roundTripperFunc func(*http.Request) (*http.Response, error)

func (f roundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }

func TestGetQuestionContentNotFound(t *testing.T) {
client := resty.New().SetTransport(roundTripperFunc(func(r *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"items":[]}`)),
Request: r,
}, nil
}))

_, err := getQuestionContent(client, ViewQuestionInputs{QuestionID: "2120178", Sub: "stackoverflow"})
if !errors.Is(err, ErrQuestionNotFound) {
t.Fatalf("expected ErrQuestionNotFound, got %v", err)
}
}