Skip to content

Commit

Permalink
Merge pull request #115 from x-motemen/dump-http
Browse files Browse the repository at this point in the history
Output debug logs for API access
  • Loading branch information
Songmu committed Oct 28, 2023
2 parents 20bf851 + 539b40f commit 9ee9694
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 2 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/reviewdog.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ jobs:
uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/setup-go@v4
with:
go-version-file: go.mod
- name: misspell
uses: reviewdog/action-misspell@v1
with:
Expand Down
60 changes: 58 additions & 2 deletions atom/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@ import (
"encoding/xml"
"fmt"
"io"
"log"
"log/slog"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
)

// Client wrapped *http.Client and some methods for accessing atom feed are added
Expand Down Expand Up @@ -88,13 +94,63 @@ func entryBody(e *Entry) (*bytes.Buffer, error) {
return body, nil
}

func (c *Client) http(method, url string, body io.Reader) (*http.Response, error) {
var blogsyncDebug = os.Getenv("BLOGSYNC_DEBUG") != ""

var debugLogger = sync.OnceValue(func() *slog.Logger {
var w io.Writer = os.Stderr
cached, err := os.UserCacheDir()
if err == nil {
logf := filepath.Join(cached, "blogsync", "tracedump.log")
if err := os.MkdirAll(filepath.Dir(logf), 0755); err == nil {
if f, err := os.OpenFile(logf, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644); err == nil {
log.Printf("trace dumps are output to %s\n", logf)
w = f
}
}
}
return slog.New(slog.NewJSONHandler(w, &slog.HandlerOptions{
Level: slog.LevelDebug,
}))
})

func (c *Client) http(method, url string, body io.Reader) (resp *http.Response, err error) {
if blogsyncDebug {
var reqBody string
if body != nil {
bb, err := io.ReadAll(body)
if err != nil {
return nil, err
}
reqBody = string(bb)
body = strings.NewReader(reqBody)
}
defer func() {
if err != nil {
return
}
bb, rerr := io.ReadAll(resp.Body)
if rerr != nil {
err = rerr
resp.Body.Close()
return
}
resp.Body = io.NopCloser(bytes.NewReader(bb))

debugLogger().Debug("traceDump",
slog.String("method", method),
slog.String("url", url),
slog.String("request", reqBody),
slog.Int("status", resp.StatusCode),
slog.String("response", string(bb)))
}()
}

req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}

resp, err := c.Client.Do(req)
resp, err = c.Client.Do(req)
if err != nil {
return nil, err
}
Expand Down

0 comments on commit 9ee9694

Please sign in to comment.