update golangci-lint to 1.43.0, fix found issues

This commit is contained in:
Dmitry Verkhoturov
2021-11-23 15:00:40 -06:00
committed by Umputun
parent 8e77acd908
commit 90e537358d
55 changed files with 290 additions and 307 deletions
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
- name: install golangci-lint and goveralls
run: |
curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s -- -b $GITHUB_WORKSPACE v1.39.0
curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s -- -b $GITHUB_WORKSPACE v1.43.0
go get -u github.com/mattn/goveralls
- name: test and lint backend
-5
View File
@@ -29,8 +29,6 @@ linters-settings:
# TODO: feel free to remove these excludes and fix the code
- hugeParam
- rangeValCopy
- singleCaseSwitch
- ifElseChain
linters:
enable:
@@ -74,6 +72,3 @@ issues:
- gosec
- dupl
exclude-use-default: false
service:
golangci-lint-version: 1.41.x
+23 -23
View File
@@ -25,7 +25,7 @@ type MemData struct {
posts map[string][]store.Comment // key is siteID
metaUsers map[string]metaUser // key is userID
metaPosts map[store.Locator]metaPost // key is post's locator
sync.RWMutex
mu sync.RWMutex
}
type metaPost struct {
@@ -61,8 +61,8 @@ func (m *MemData) Create(comment store.Comment) (commentID string, err error) {
return "", errors.Errorf("post %s is read-only", comment.Locator.URL)
}
m.Lock()
defer m.Unlock()
m.mu.Lock()
defer m.mu.Unlock()
comments := m.posts[comment.Locator.SiteID]
for _, c := range comments { // don't allow duplicated IDs
if c.ID == comment.ID {
@@ -76,8 +76,8 @@ func (m *MemData) Create(comment store.Comment) (commentID string, err error) {
// Find returns all comments for post and sorts results
func (m *MemData) Find(req engine.FindRequest) (comments []store.Comment, err error) {
m.RLock()
defer m.RUnlock()
m.mu.RLock()
defer m.mu.RUnlock()
comments = []store.Comment{}
@@ -132,22 +132,22 @@ func (m *MemData) Find(req engine.FindRequest) (comments []store.Comment, err er
// Get returns comment for locator.URL and commentID string
func (m *MemData) Get(req engine.GetRequest) (comment store.Comment, err error) {
m.RLock()
defer m.RUnlock()
m.mu.RLock()
defer m.mu.RUnlock()
return m.get(req.Locator, req.CommentID)
}
// Update updates comment for locator.URL with mutable part of comment
func (m *MemData) Update(comment store.Comment) error {
m.Lock()
defer m.Unlock()
m.mu.Lock()
defer m.mu.Unlock()
return m.updateComment(comment)
}
// Count returns number of comments for post or user
func (m *MemData) Count(req engine.FindRequest) (count int, err error) {
m.RLock()
defer m.RUnlock()
m.mu.RLock()
defer m.mu.RUnlock()
switch {
case req.Locator.URL != "": // comment's count for post
@@ -167,8 +167,8 @@ func (m *MemData) Count(req engine.FindRequest) (count int, err error) {
// Info get post(s) meta info
func (m *MemData) Info(req engine.InfoRequest) (res []store.PostInfo, err error) {
m.RLock()
defer m.RUnlock()
m.mu.RLock()
defer m.mu.RUnlock()
res = []store.PostInfo{}
if req.Locator.URL != "" { // post info
@@ -240,8 +240,8 @@ func (m *MemData) Info(req engine.InfoRequest) (res []store.PostInfo, err error)
// Flag sets and gets flag values
func (m *MemData) Flag(req engine.FlagRequest) (val bool, err error) {
m.Lock()
defer m.Unlock()
m.mu.Lock()
defer m.mu.Unlock()
if req.Update == engine.FlagNonSet { // read flag value, no update requested
return m.checkFlag(req), nil
@@ -253,8 +253,8 @@ func (m *MemData) Flag(req engine.FlagRequest) (val bool, err error) {
// ListFlags get list of flagged keys, like blocked & verified user
// works for full locator (post flags) or with userID
func (m *MemData) ListFlags(req engine.FlagRequest) (res []interface{}, err error) {
m.RLock()
defer m.RUnlock()
m.mu.RLock()
defer m.mu.RUnlock()
res = []interface{}{}
@@ -290,8 +290,8 @@ func (m *MemData) UserDetail(req engine.UserDetailRequest) ([]engine.UserDetailE
return nil, errors.New("userid cannot be empty in request for single detail")
}
m.Lock()
defer m.Unlock()
m.mu.Lock()
defer m.mu.Unlock()
if req.Update == "" { // read detail value, no update requested
return m.getUserDetail(req)
@@ -302,8 +302,8 @@ func (m *MemData) UserDetail(req engine.UserDetailRequest) ([]engine.UserDetailE
// list of all details returned in case request is a read request
// (Update is not set) and does not have UserID or Detail set
if req.Update == "" && req.UserID == "" { // read list of all details
m.Lock()
defer m.Unlock()
m.mu.Lock()
defer m.mu.Unlock()
return m.listDetails(req.Locator)
}
return nil, errors.New("unsupported request with userdetail all")
@@ -315,8 +315,8 @@ func (m *MemData) UserDetail(req engine.UserDetailRequest) ([]engine.UserDetailE
// Delete post(s), user, comment, user details, or everything
func (m *MemData) Delete(req engine.DeleteRequest) error {
m.Lock()
defer m.Unlock()
m.mu.Lock()
defer m.mu.Unlock()
switch {
case req.UserDetail != "": // delete user detail
+17 -17
View File
@@ -22,7 +22,7 @@ type MemImage struct {
imagesStaging map[string][]byte
images map[string][]byte
insertTime map[string]time.Time
sync.RWMutex
mu sync.RWMutex
}
// NewMemImageStore makes admin Store in memory.
@@ -37,18 +37,18 @@ func NewMemImageStore() *MemImage {
// Save stores image with passed id to staging
func (m *MemImage) Save(id string, img []byte) error {
m.Lock()
m.mu.Lock()
m.imagesStaging[id] = img
m.insertTime[id] = time.Now()
m.Unlock()
m.mu.Unlock()
return nil
}
// ResetCleanupTimer resets cleanup timer for the image
func (m *MemImage) ResetCleanupTimer(id string) error {
m.Lock()
defer m.Unlock()
m.mu.Lock()
defer m.mu.Unlock()
if _, ok := m.insertTime[id]; ok {
m.insertTime[id] = time.Now()
return nil
@@ -58,12 +58,12 @@ func (m *MemImage) ResetCleanupTimer(id string) error {
// Load image by ID
func (m *MemImage) Load(id string) ([]byte, error) {
m.RLock()
m.mu.RLock()
img, ok := m.images[id]
if !ok {
img, ok = m.imagesStaging[id]
}
m.RUnlock()
m.mu.RUnlock()
if !ok {
return nil, errors.Errorf("image %s not found", id)
}
@@ -72,16 +72,16 @@ func (m *MemImage) Load(id string) ([]byte, error) {
// Commit moves image from staging to permanent
func (m *MemImage) Commit(id string) error {
m.RLock()
m.mu.RLock()
img, ok := m.imagesStaging[id]
m.RUnlock()
m.mu.RUnlock()
if !ok {
return errors.Errorf("failed to commit %s, not found in staging", id)
}
m.Lock()
m.mu.Lock()
m.images[id] = img
m.Unlock()
m.mu.Unlock()
return nil
}
@@ -90,7 +90,7 @@ func (m *MemImage) Commit(id string) error {
func (m *MemImage) Cleanup(_ context.Context, ttl time.Duration) error {
var idsToRemove []string
m.RLock()
m.mu.RLock()
for id, t := range m.insertTime {
age := time.Since(t)
if age > ttl {
@@ -98,27 +98,27 @@ func (m *MemImage) Cleanup(_ context.Context, ttl time.Duration) error {
idsToRemove = append(idsToRemove, id)
}
}
m.RUnlock()
m.mu.RUnlock()
m.Lock()
m.mu.Lock()
for _, id := range idsToRemove {
delete(m.insertTime, id)
delete(m.imagesStaging, id)
}
m.Unlock()
m.mu.Unlock()
return nil
}
// Info returns meta information about storage
func (m *MemImage) Info() (image.StoreInfo, error) {
var ts time.Time
m.RLock()
m.mu.RLock()
for _, t := range m.insertTime {
if ts.IsZero() || t.Before(ts) {
ts = t
}
}
m.RUnlock()
m.mu.RUnlock()
return image.StoreInfo{FirstStagingImageTS: ts}, nil
}
@@ -10,7 +10,6 @@ import (
"context"
"encoding/base64"
"io"
"io/ioutil"
"strings"
"testing"
"time"
@@ -43,7 +42,7 @@ func gopherPNG() io.Reader { return base64.NewDecoder(base64.StdEncoding, string
func TestMemImage_LoadAfterSave(t *testing.T) {
svc := NewMemImageStore()
gopher, err := ioutil.ReadAll(gopherPNG())
gopher, err := io.ReadAll(gopherPNG())
assert.NoError(t, err)
img, err := svc.Load("test_id")
@@ -85,7 +84,7 @@ func TestMemImage_Cleanup(t *testing.T) {
func TestMemImage_Info(t *testing.T) {
svc := NewMemImageStore()
gopher, err := ioutil.ReadAll(gopherPNG())
gopher, err := io.ReadAll(gopherPNG())
assert.NoError(t, err)
// get info on empty storage, should be zero
@@ -11,7 +11,6 @@ import (
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"testing"
@@ -46,7 +45,7 @@ const gopher = "iVBORw0KGgoAAAANSUhEUgAAAEsAAAA8CAAAAAALAhhPAAAFfUlEQVRYw62XeWwU
func gopherPNG() io.Reader { return base64.NewDecoder(base64.StdEncoding, strings.NewReader(gopher)) }
func gopherPNGBytes() []byte {
img, _ := ioutil.ReadAll(gopherPNG())
img, _ := io.ReadAll(gopherPNG())
return img
}
+2 -2
View File
@@ -41,7 +41,7 @@ func (ec *BackupCommand) Execute(_ []string) error {
ctx, cancel := context.WithTimeout(context.Background(), ec.Timeout)
defer cancel()
exportURL := fmt.Sprintf("%s/api/v1/admin/export?mode=file&site=%s", ec.RemarkURL, ec.Site)
req, err := http.NewRequest(http.MethodGet, exportURL, nil)
req, err := http.NewRequest(http.MethodGet, exportURL, http.NoBody)
if err != nil {
return errors.Wrapf(err, "can't make export request for %s", exportURL)
}
@@ -66,7 +66,7 @@ func (ec *BackupCommand) Execute(_ []string) error {
if err != nil {
return errors.Wrapf(err, "can't create backup file %s", fname)
}
defer func() {
defer func() { //nolint:gosec // false positive on defer without error check when it's checked here
if err = fh.Close(); err != nil {
log.Printf("[WARN] failed to close file %s, %s", fh.Name(), err)
}
+1 -2
View File
@@ -2,7 +2,6 @@ package cmd
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
@@ -31,7 +30,7 @@ func TestBackup_Execute(t *testing.T) {
assert.NoError(t, err)
defer os.Remove("/tmp/remark-test.export")
data, err := ioutil.ReadFile("/tmp/remark-test.export")
data, err := os.ReadFile("/tmp/remark-test.export")
require.NoError(t, err)
assert.Equal(t, "blah\nblah2\n12345678\n", string(data))
}
+2 -2
View File
@@ -193,7 +193,7 @@ func (cc *CleanupCommand) listComments(postURL string) ([]store.Comment, error)
func (cc *CleanupCommand) deleteComment(c store.Comment) error {
deleteURL := fmt.Sprintf("%s/api/v1/admin/comment/%s?site=%s&url=%s&format=plain", cc.RemarkURL, c.ID, cc.Site, c.Locator.URL)
req, err := http.NewRequest("DELETE", deleteURL, nil)
req, err := http.NewRequest("DELETE", deleteURL, http.NoBody)
if err != nil {
return errors.Wrapf(err, "failed to make delete request for comment %s, %s", c.ID, c.Locator.URL)
}
@@ -215,7 +215,7 @@ func (cc *CleanupCommand) deleteComment(c store.Comment) error {
func (cc *CleanupCommand) setTitle(c store.Comment) error {
titleURL := fmt.Sprintf("%s/api/v1/admin/title/%s?site=%s&url=%s&format=plain", cc.RemarkURL, c.ID, cc.Site, c.Locator.URL)
req, err := http.NewRequest("PUT", titleURL, nil)
req, err := http.NewRequest("PUT", titleURL, http.NoBody)
if err != nil {
return errors.Wrapf(err, "failed to make title request for comment %s, %s", c.ID, c.Locator.URL)
}
+3 -3
View File
@@ -4,7 +4,7 @@ package cmd
import (
"bytes"
"io/ioutil"
"io"
"net/http"
"os"
"path/filepath"
@@ -103,7 +103,7 @@ func resetEnv(envs ...string) {
// responseError returns error with status and response body
func responseError(resp *http.Response) error {
body, e := ioutil.ReadAll(resp.Body)
body, e := io.ReadAll(resp.Body)
if e != nil {
body = []byte("")
}
@@ -113,7 +113,7 @@ func responseError(resp *http.Response) error {
// mkdir -p for all dirs
func makeDirs(dirs ...string) error {
for _, dir := range dirs {
if err := os.MkdirAll(dir, 0700); err != nil { // If path is already a directory, MkdirAll does nothing
if err := os.MkdirAll(dir, 0o700); err != nil { // If path is already a directory, MkdirAll does nothing
return errors.Wrapf(err, "can't make directory %s", dir)
}
}
+1 -2
View File
@@ -5,7 +5,6 @@ import (
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
@@ -58,7 +57,7 @@ func (ic *ImportCommand) Execute(_ []string) error {
return responseError(resp)
}
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return errors.Wrap(err, "can't get response from importer")
}
+3 -3
View File
@@ -2,7 +2,7 @@ package cmd
import (
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"testing"
@@ -20,7 +20,7 @@ func TestImport_Execute(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, r.URL.Path, "/api/v1/admin/import")
assert.Equal(t, "POST", r.Method)
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
assert.NoError(t, err)
assert.Equal(t, "blah\nblah2\n12345678\n", string(body))
@@ -97,7 +97,7 @@ func TestImport_ExecuteTimeout(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, r.URL.Path, "/api/v1/admin/import")
assert.Equal(t, "POST", r.Method)
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
assert.NoError(t, err)
assert.Equal(t, "blah\nblah2\n12345678\n", string(body))
time.Sleep(500 * time.Millisecond)
+2 -2
View File
@@ -3,7 +3,7 @@ package cmd
import (
"context"
"fmt"
"io/ioutil"
"io"
"net/http"
"os"
"time"
@@ -55,7 +55,7 @@ func (rc *RemapCommand) Execute(_ []string) error {
return responseError(resp)
}
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return errors.Wrap(err, "can't get response")
}
+2 -2
View File
@@ -1,7 +1,7 @@
package cmd
import (
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"testing"
@@ -18,7 +18,7 @@ func TestRemap_Execute(t *testing.T) {
assert.Equal(t, r.URL.Path, "/api/v1/admin/remap")
assert.Equal(t, "POST", r.Method)
assert.Equal(t, "remark", r.URL.Query().Get("site"))
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
assert.NoError(t, err)
assert.Equal(t, "http://oldsite.com* https://newsite.com*\nhttp://oldsite.com/from-old-page/1 https://newsite.com/to-new-page/1", string(body))
+2 -2
View File
@@ -2,7 +2,7 @@ package cmd
import (
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"testing"
@@ -19,7 +19,7 @@ func TestRestore_Execute(t *testing.T) {
assert.Equal(t, r.URL.Path, "/api/v1/admin/import")
assert.Equal(t, "POST", r.Method)
assert.Equal(t, "native", r.URL.Query().Get("provider"))
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
assert.NoError(t, err)
assert.Equal(t, "blah\nblah2\n12345678\n", string(body))
+1 -2
View File
@@ -3,7 +3,6 @@ package cmd
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
@@ -878,7 +877,7 @@ func (s *ServerCommand) loadEmailTemplate() (string, error) {
file, err = fs.ReadFile(s.Auth.Email.MsgTemplate)
} else {
// deprecated loading from an external file, should be removed before v1.9.0
file, err = ioutil.ReadFile(s.Auth.Email.MsgTemplate)
file, err = os.ReadFile(s.Auth.Email.MsgTemplate)
log.Printf("[INFO] template %s will be read from disk", s.Auth.Email.MsgTemplate)
}
+11 -11
View File
@@ -4,7 +4,7 @@ import (
"context"
"crypto/tls"
"fmt"
"io/ioutil"
"io"
"math/rand"
"net"
"net/http"
@@ -39,7 +39,7 @@ func TestServerApp(t *testing.T) {
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, 200, resp.StatusCode)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t, "pong", string(body))
@@ -54,7 +54,7 @@ func TestServerApp(t *testing.T) {
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, http.StatusCreated, resp.StatusCode)
body, _ = ioutil.ReadAll(resp.Body)
body, _ = io.ReadAll(resp.Body)
t.Log(string(body))
email, err := app.dataService.AdminStore.Email("")
@@ -84,7 +84,7 @@ func TestServerApp_DevMode(t *testing.T) {
resp, err := http.Get(fmt.Sprintf("http://localhost:%d/api/v1/ping", port))
require.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.NoError(t, resp.Body.Close())
assert.Equal(t, "pong", string(body))
@@ -113,7 +113,7 @@ func TestServerApp_AnonMode(t *testing.T) {
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t, "pong", string(body))
@@ -259,7 +259,7 @@ func TestServerApp_WithSSL(t *testing.T) {
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, 200, resp.StatusCode)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t, "pong", string(body))
@@ -295,7 +295,7 @@ func TestServerApp_WithRemote(t *testing.T) {
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, 200, resp.StatusCode)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t, "pong", string(body))
@@ -547,20 +547,20 @@ func TestServerAuthHooks(t *testing.T) {
req.Header.Set("X-JWT", tkNoAud)
resp, err = client.Do(req)
require.NoError(t, err)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.Equal(t, http.StatusUnauthorized, resp.StatusCode, "user without aud claim rejected, \n"+tkNoAud+"\n"+string(body))
// block user dev as admin
req, err = http.NewRequest(http.MethodPut,
fmt.Sprintf("http://localhost:%d/api/v1/admin/user/dev?site=remark&block=1&ttl=10d", port), nil)
fmt.Sprintf("http://localhost:%d/api/v1/admin/user/dev?site=remark&block=1&ttl=10d", port), http.NoBody)
assert.NoError(t, err)
req.SetBasicAuth("admin", "password")
resp, err = client.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode, "user dev blocked")
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
t.Log(string(b))
@@ -572,7 +572,7 @@ func TestServerAuthHooks(t *testing.T) {
req.Header.Set("X-JWT", tk)
resp, err = client.Do(req)
require.NoError(t, err)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.True(t, resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusUnauthorized,
+1 -1
View File
@@ -90,7 +90,7 @@ func getDump() string {
// nolint:gochecknoinits // can't avoid it in this place
func init() {
// catch SIGQUIT and print stack traces
sigChan := make(chan os.Signal)
sigChan := make(chan os.Signal, 1)
go func() {
for range sigChan {
log.Printf("[INFO] SIGQUIT detected, dump:\n%s", getDump())
+3 -2
View File
@@ -2,6 +2,7 @@ package main
import (
"fmt"
"io"
"io/ioutil"
"math/rand"
"net"
@@ -54,7 +55,7 @@ func Test_Main(t *testing.T) {
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, 200, resp.StatusCode)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t, "pong", string(body))
}
@@ -69,7 +70,7 @@ func TestMain_WithWebhook(t *testing.T) {
atomic.StoreInt32(&webhookSent, 1)
assert.Equal(t, "application/json", r.Header.Get("Content-Type"))
b, e := ioutil.ReadAll(r.Body)
b, e := io.ReadAll(r.Body)
defer r.Body.Close()
assert.Nil(t, e)
+7 -3
View File
@@ -4,7 +4,6 @@ import (
"compress/gzip"
"context"
"fmt"
"io/ioutil"
"os"
"sort"
"strings"
@@ -69,15 +68,20 @@ func (ab AutoBackup) makeBackup() (string, error) {
}
func (ab AutoBackup) removeOldBackupFiles() {
files, err := ioutil.ReadDir(ab.BackupLocation)
files, err := os.ReadDir(ab.BackupLocation)
if err != nil {
log.Printf("[WARN] can't read files in backup directory %s, %s", ab.BackupLocation, err)
return
}
backFiles := []os.FileInfo{}
for _, file := range files {
info, e := file.Info()
if e != nil {
log.Printf("[WARN] can't read info for directory %s, %s", file.Name(), e)
return
}
if strings.HasPrefix(file.Name(), "backup-"+ab.SiteID) {
backFiles = append(backFiles, file)
backFiles = append(backFiles, info)
}
}
sort.Slice(backFiles, func(i int, j int) bool { return backFiles[i].Name() < backFiles[j].Name() })
+6 -7
View File
@@ -4,7 +4,6 @@ import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"testing"
"time"
@@ -17,20 +16,20 @@ func TestBackup_RemoveOldBackupFiles(t *testing.T) {
loc := "/tmp/remark-backups.test"
defer os.RemoveAll(loc)
assert.NoError(t, os.MkdirAll(loc, 0700))
assert.NoError(t, os.MkdirAll(loc, 0o700))
for i := 1; i <= 10; i++ {
fname := fmt.Sprintf("%s/backup-site1-201712%02d.gz", loc, i)
err := ioutil.WriteFile(fname, []byte("blah"), 0600)
err := os.WriteFile(fname, []byte("blah"), 0o600)
assert.NoError(t, err)
}
fname := fmt.Sprintf("%s/backup-site2-20171210.gz", loc)
err := ioutil.WriteFile(fname, []byte("blah"), 0600)
err := os.WriteFile(fname, []byte("blah"), 0o600)
assert.NoError(t, err)
bk := AutoBackup{BackupLocation: loc, SiteID: "site1", KeepMax: 3}
bk.removeOldBackupFiles()
ff, err := ioutil.ReadDir(loc)
ff, err := os.ReadDir(loc)
assert.NoError(t, err)
require.Equal(t, 4, len(ff), "should keep 4 files - 3 kept for sit1, and one for site2")
assert.Equal(t, "backup-site1-20171208.gz", ff[0].Name())
@@ -42,7 +41,7 @@ func TestBackup_RemoveOldBackupFiles(t *testing.T) {
func TestBackup_MakeBackup(t *testing.T) {
loc := "/tmp/remark-backups.test"
defer os.RemoveAll(loc)
assert.NoError(t, os.MkdirAll(loc, 0700))
assert.NoError(t, os.MkdirAll(loc, 0o700))
bk := AutoBackup{BackupLocation: loc, SiteID: "site1", KeepMax: 3, Exporter: &mockExporter{}}
fname, err := bk.makeBackup()
@@ -58,7 +57,7 @@ func TestBackup_MakeBackup(t *testing.T) {
func TestBackup_Do(t *testing.T) {
loc := "/tmp/remark-backups.test"
defer os.RemoveAll(loc)
assert.NoError(t, os.MkdirAll(loc, 0700))
assert.NoError(t, os.MkdirAll(loc, 0o700))
ctx, cancel := context.WithCancel(context.Background())
go func() {
+1 -3
View File
@@ -101,9 +101,7 @@ func (d *Disqus) convert(r io.Reader, siteID string) (ch chan store.Comment) {
break
}
switch se := t.(type) {
case xml.StartElement:
if se, ok := t.(xml.StartElement); ok {
if se.Name.Local == "thread" {
stats.inpThreads++
thread := disqusThread{}
+1 -2
View File
@@ -3,7 +3,6 @@ package migrator
import (
"errors"
"io"
"io/ioutil"
"strings"
)
@@ -30,7 +29,7 @@ func NewURLMapper(reader io.Reader) (Mapper, error) {
// https://www.myblog.com/blog/1/ https://myblog.com/blog/1/
// https://www.myblog.com/* https://myblog.com/*
func (u *URLMapper) loadRules(reader io.Reader) error {
data, err := ioutil.ReadAll(reader)
data, err := io.ReadAll(reader)
if err != nil {
return err
}
+1 -1
View File
@@ -77,7 +77,7 @@ func ImportComments(p ImportParams) (int, error) {
return 0, errors.Wrapf(err, "can't open import file %s", p.InputFile)
}
defer func() {
defer func() { //nolint:gosec // false positive on defer without error check when it's checked here
if err = fh.Close(); err != nil {
log.Printf("[WARN] can't close %s, %s", p.InputFile, err)
}
+2 -3
View File
@@ -1,7 +1,6 @@
package migrator
import (
"io/ioutil"
"os"
"testing"
"time"
@@ -43,7 +42,7 @@ func TestMigrator_ImportWordPress(t *testing.T) {
os.Remove("/tmp/wordpress-test.xml")
}()
err := ioutil.WriteFile("/tmp/wordpress-test.xml", []byte(xmlTestWP), 0600)
err := os.WriteFile("/tmp/wordpress-test.xml", []byte(xmlTestWP), 0o600)
require.NoError(t, err)
b, err := engine.NewBoltDB(bolt.Options{}, engine.BoltSite{FileName: "/tmp/remark-test.db", SiteID: "test"})
@@ -94,7 +93,7 @@ func TestMigrator_ImportNative(t *testing.T) {
data := `{"version":1} {"id":"efbc17f177ee1a1c0ee6e1e025749966ec071adc","pid":"","text":"some text, <a href=\"http://radio-t.com\" rel=\"nofollow\">link</a>","user":{"name":"user name","id":"user1","picture":"","profile":"","admin":false},"locator":{"site":"radio-t","url":"https://radio-t.com"},"score":0,"votes":{},"time":"2017-12-20T15:18:22-06:00"}` + "\n" +
`{"id":"afbc17f177ee1a1c0ee6e1e025749966ec071adc","pid":"efbc17f177ee1a1c0ee6e1e025749966ec071adc","text":"some text2, <a href=\"http://radio-t.com\" rel=\"nofollow\">link</a>","user":{"name":"user name","id":"user1","picture":"","profile":"","admin":false},"locator":{"site":"radio-t","url":"https://radio-t.com"},"score":0,"votes":{},"time":"2017-12-20T15:18:23-06:00"}` + "\n"
err := ioutil.WriteFile("/tmp/disqus-test.r42", []byte(data), 0600)
err := os.WriteFile("/tmp/disqus-test.r42", []byte(data), 0o600)
require.NoError(t, err)
b, err := engine.NewBoltDB(bolt.Options{}, engine.BoltSite{FileName: "/tmp/remark-test.db", SiteID: "radio-t"})
+1 -2
View File
@@ -107,8 +107,7 @@ func (w *WordPress) convert(r io.Reader, siteID string) chan store.Comment {
break
}
switch el := t.(type) {
case xml.StartElement:
if el, ok := t.(xml.StartElement); ok {
if el.Name.Local == "item" {
stats.inpItems++
item := wpItem{}
+4 -4
View File
@@ -144,10 +144,10 @@ func (t *Telegram) sendMessage(ctx context.Context, b []byte, chatID string) err
func buildMessage(req Request) ([]byte, error) {
commentURLPrefix := req.Comment.Locator.URL + uiNav
msg := fmt.Sprintf(`<a href="%s">%s</a>`, commentURLPrefix+req.Comment.ID, escapeTelegramText(req.Comment.User.Name))
msg := fmt.Sprintf(`<a href=%q>%s</a>`, commentURLPrefix+req.Comment.ID, escapeTelegramText(req.Comment.User.Name))
if req.Comment.ParentID != "" {
msg += fmt.Sprintf(" -> <a href=\"%s\">%s</a>", commentURLPrefix+req.parent.ID, escapeTelegramText(req.parent.User.Name))
msg += fmt.Sprintf(" -> <a href=%q>%s</a>", commentURLPrefix+req.parent.ID, escapeTelegramText(req.parent.User.Name))
}
msg += fmt.Sprintf("\n\n%s", telegramSupportedHTML(req.Comment.Text))
@@ -157,7 +157,7 @@ func buildMessage(req Request) ([]byte, error) {
}
if req.Comment.PostTitle != "" {
msg += fmt.Sprintf("\n\n↦ <a href=\"%s\">%s</a>", req.Comment.Locator.URL, escapeTelegramText(req.Comment.PostTitle))
msg += fmt.Sprintf("\n\n↦ <a href=%q>%s</a>", req.Comment.Locator.URL, escapeTelegramText(req.Comment.PostTitle))
}
body := telegramMsg{Text: msg, ParseMode: "HTML"}
@@ -421,7 +421,7 @@ func (t *Telegram) Request(ctx context.Context, method string, b []byte, data in
var req *http.Request
var err error
if b == nil {
req, err = http.NewRequestWithContext(ctx, "GET", url, nil)
req, err = http.NewRequestWithContext(ctx, "GET", url, http.NoBody)
} else {
req, err = http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(b))
req.Header.Set("Content-Type", "application/json; charset=utf-8")
+2 -2
View File
@@ -4,7 +4,7 @@ import (
"bytes"
"context"
"fmt"
"io/ioutil"
"io"
"net/http"
"strings"
"text/template"
@@ -90,7 +90,7 @@ func (t *Webhook) Send(ctx context.Context, req Request) error {
if resp.StatusCode != http.StatusOK {
errMsg := fmt.Sprintf("webhook request failed with non-OK status code: %d", resp.StatusCode)
respBody, e := ioutil.ReadAll(resp.Body)
respBody, e := io.ReadAll(resp.Body)
if e != nil {
return fmt.Errorf(errMsg)
}
+5 -5
View File
@@ -4,7 +4,7 @@ import (
"bytes"
"context"
"errors"
"io/ioutil"
"io"
"net/http"
"testing"
@@ -23,7 +23,7 @@ func (c funcWebhookClient) Do(r *http.Request) (*http.Response, error) {
var okWebhookClient = funcWebhookClient(func(*http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewBufferString("ok")),
Body: io.NopCloser(bytes.NewBufferString("ok")),
}, nil
})
@@ -75,7 +75,7 @@ func TestWebhook_Send(t *testing.T) {
return &http.Response{
StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewBufferString("")),
Body: io.NopCloser(bytes.NewBufferString("")),
}, nil
}), WebhookParams{
WebhookURL: "https://example.org/webhook",
@@ -116,7 +116,7 @@ func TestWebhook_Send(t *testing.T) {
wh, err = NewWebhook(funcWebhookClient(func(*http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusNotFound,
Body: ioutil.NopCloser(bytes.NewBufferString("not found")),
Body: io.NopCloser(bytes.NewBufferString("not found")),
}, nil
}), WebhookParams{
WebhookURL: "http:/example.org/invalid-url",
@@ -129,7 +129,7 @@ func TestWebhook_Send(t *testing.T) {
wh, err = NewWebhook(funcWebhookClient(func(*http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusNotFound,
Body: ioutil.NopCloser(errReader{}),
Body: io.NopCloser(errReader{}),
}, nil
}), WebhookParams{
WebhookURL: "http:/example.org/invalid-url",
+31 -31
View File
@@ -5,7 +5,7 @@ import (
"compress/gzip"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"os"
@@ -48,7 +48,7 @@ func TestAdmin_Delete(t *testing.T) {
resp, err := post(t, ts.URL+"/api/v1/counts?site=remark42", `["https://radio-t.com/blah","https://radio-t.com/blah2"]`)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
bb, err := ioutil.ReadAll(resp.Body)
bb, err := io.ReadAll(resp.Body)
assert.NoError(t, resp.Body.Close())
assert.NoError(t, err)
j := []store.PostInfo{}
@@ -59,7 +59,7 @@ func TestAdmin_Delete(t *testing.T) {
// delete a comment
req, err := http.NewRequest(http.MethodDelete,
fmt.Sprintf("%s/api/v1/admin/comment/%s?site=remark42&url=https://radio-t.com/blah", ts.URL, id1), nil)
fmt.Sprintf("%s/api/v1/admin/comment/%s?site=remark42&url=https://radio-t.com/blah", ts.URL, id1), http.NoBody)
require.NoError(t, err)
requireAdminOnly(t, req)
resp, err = sendReq(t, req, adminUmputunToken)
@@ -97,7 +97,7 @@ func TestAdmin_Delete(t *testing.T) {
resp, err = post(t, ts.URL+"/api/v1/counts?site=remark42", `["https://radio-t.com/blah","https://radio-t.com/blah2"]`)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
bb, err = ioutil.ReadAll(resp.Body)
bb, err = io.ReadAll(resp.Body)
assert.NoError(t, resp.Body.Close())
assert.NoError(t, err)
j = []store.PostInfo{}
@@ -136,7 +136,7 @@ func TestAdmin_Title(t *testing.T) {
addComment(t, c2, ts)
req, err := http.NewRequest(http.MethodPut,
fmt.Sprintf("%s/api/v1/admin/title/%s?site=remark42&url=%s/post1", ts.URL, id1, tss.URL), nil)
fmt.Sprintf("%s/api/v1/admin/title/%s?site=remark42&url=%s/post1", ts.URL, id1, tss.URL), http.NoBody)
assert.NoError(t, err)
requireAdminOnly(t, req)
resp, err := sendReq(t, req, adminUmputunToken)
@@ -171,7 +171,7 @@ func TestAdmin_DeleteUser(t *testing.T) {
_, err = srv.DataService.Create(c3)
assert.NoError(t, err)
req, err := http.NewRequest(http.MethodDelete, fmt.Sprintf("%s/api/v1/admin/user/%s?site=remark42", ts.URL, "id2"), nil)
req, err := http.NewRequest(http.MethodDelete, fmt.Sprintf("%s/api/v1/admin/user/%s?site=remark42", ts.URL, "id2"), http.NoBody)
assert.NoError(t, err)
requireAdminOnly(t, req)
resp, err := sendReq(t, req, adminUmputunToken)
@@ -220,7 +220,7 @@ func TestAdmin_Pin(t *testing.T) {
pin := func(val int) int {
client := http.Client{}
req, err := http.NewRequest(http.MethodPut,
fmt.Sprintf("%s/api/v1/admin/pin/%s?site=remark42&url=https://radio-t.com/blah&pin=%d", ts.URL, id1, val), nil)
fmt.Sprintf("%s/api/v1/admin/pin/%s?site=remark42&url=https://radio-t.com/blah&pin=%d", ts.URL, id1, val), http.NoBody)
assert.NoError(t, err)
requireAdminOnly(t, req)
req.SetBasicAuth("admin", "password")
@@ -271,12 +271,12 @@ func TestAdmin_Block(t *testing.T) {
if ttl != "" {
url = url + "&ttl=" + ttl
}
req, err := http.NewRequest(http.MethodPut, url, nil)
req, err := http.NewRequest(http.MethodPut, url, http.NoBody)
assert.NoError(t, err)
requireAdminOnly(t, req)
resp, err := sendReq(t, req, adminUmputunToken)
require.NoError(t, err)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
assert.NoError(t, err)
require.NoError(t, resp.Body.Close())
return resp.StatusCode, body
@@ -308,7 +308,7 @@ func TestAdmin_Block(t *testing.T) {
resp, err := post(t, ts.URL+"/api/v1/counts?site=remark42", `["https://radio-t.com/blah"]`)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.NoError(t, resp.Body.Close())
pi = []store.PostInfo{}
@@ -380,7 +380,7 @@ func TestAdmin_BlockedList(t *testing.T) {
// block user1
req, err := http.NewRequest(http.MethodPut,
fmt.Sprintf("%s/api/v1/admin/user/%s?site=remark42&block=%d", ts.URL, "user1", 1), nil)
fmt.Sprintf("%s/api/v1/admin/user/%s?site=remark42&block=%d", ts.URL, "user1", 1), http.NoBody)
assert.NoError(t, err)
res, err := sendReq(t, req, adminUmputunToken)
require.NoError(t, err)
@@ -389,14 +389,14 @@ func TestAdmin_BlockedList(t *testing.T) {
// block user2
req, err = http.NewRequest(http.MethodPut,
fmt.Sprintf("%s/api/v1/admin/user/%s?site=remark42&block=%d&ttl=150ms", ts.URL, "user2", 1), nil)
fmt.Sprintf("%s/api/v1/admin/user/%s?site=remark42&block=%d&ttl=150ms", ts.URL, "user2", 1), http.NoBody)
assert.NoError(t, err)
res, err = sendReq(t, req, adminUmputunToken)
require.NoError(t, err)
require.NoError(t, res.Body.Close())
assert.Equal(t, 200, res.StatusCode)
req, err = http.NewRequest("GET", ts.URL+"/api/v1/admin/blocked?site=remark42", nil)
req, err = http.NewRequest("GET", ts.URL+"/api/v1/admin/blocked?site=remark42", http.NoBody)
require.NoError(t, err)
res, err = sendReq(t, req, adminUmputunToken)
require.NoError(t, err)
@@ -413,7 +413,7 @@ func TestAdmin_BlockedList(t *testing.T) {
t.Logf("%+v", users)
time.Sleep(150 * time.Millisecond)
req, err = http.NewRequest("GET", ts.URL+"/api/v1/admin/blocked?site=remark42", nil)
req, err = http.NewRequest("GET", ts.URL+"/api/v1/admin/blocked?site=remark42", http.NoBody)
require.NoError(t, err)
res, err = sendReq(t, req, adminUmputunToken)
require.NoError(t, err)
@@ -445,7 +445,7 @@ func TestAdmin_ReadOnly(t *testing.T) {
// set post to read-only
req, err := http.NewRequest(http.MethodPut,
fmt.Sprintf("%s/api/v1/admin/readonly?site=remark42&url=https://radio-t.com/blah&ro=1", ts.URL), nil)
fmt.Sprintf("%s/api/v1/admin/readonly?site=remark42&url=https://radio-t.com/blah&ro=1", ts.URL), http.NoBody)
assert.NoError(t, err)
resp, err := sendReq(t, req, "") // non-admin user
require.NoError(t, err)
@@ -473,7 +473,7 @@ func TestAdmin_ReadOnly(t *testing.T) {
// reset post's read-only
req, err = http.NewRequest(http.MethodPut,
fmt.Sprintf("%s/api/v1/admin/readonly?site=remark42&url=https://radio-t.com/blah&ro=0", ts.URL), nil)
fmt.Sprintf("%s/api/v1/admin/readonly?site=remark42&url=https://radio-t.com/blah&ro=0", ts.URL), http.NoBody)
assert.NoError(t, err)
resp, err = sendReq(t, req, adminUmputunToken)
require.NoError(t, err)
@@ -502,7 +502,7 @@ func TestAdmin_ReadOnlyNoComments(t *testing.T) {
// set post to read-only
req, err := http.NewRequest(http.MethodPut,
fmt.Sprintf("%s/api/v1/admin/readonly?site=remark42&url=https://radio-t.com/blah&ro=1", ts.URL), nil)
fmt.Sprintf("%s/api/v1/admin/readonly?site=remark42&url=https://radio-t.com/blah&ro=1", ts.URL), http.NoBody)
assert.NoError(t, err)
requireAdminOnly(t, req)
resp, err := sendReq(t, req, adminUmputunToken)
@@ -538,7 +538,7 @@ func TestAdmin_ReadOnlyWithAge(t *testing.T) {
// set post to read-only
req, err := http.NewRequest(http.MethodPut,
fmt.Sprintf("%s/api/v1/admin/readonly?site=remark42&url=https://radio-t.com/blah&ro=1", ts.URL), nil)
fmt.Sprintf("%s/api/v1/admin/readonly?site=remark42&url=https://radio-t.com/blah&ro=1", ts.URL), http.NoBody)
assert.NoError(t, err)
requireAdminOnly(t, req)
resp, err := sendReq(t, req, adminUmputunToken)
@@ -551,7 +551,7 @@ func TestAdmin_ReadOnlyWithAge(t *testing.T) {
// reset post's read-only
req, err = http.NewRequest(http.MethodPut,
fmt.Sprintf("%s/api/v1/admin/readonly?site=remark42&url=https://radio-t.com/blah&ro=0", ts.URL), nil)
fmt.Sprintf("%s/api/v1/admin/readonly?site=remark42&url=https://radio-t.com/blah&ro=0", ts.URL), http.NoBody)
assert.NoError(t, err)
resp, err = sendReq(t, req, adminUmputunToken)
require.NoError(t, err)
@@ -580,7 +580,7 @@ func TestAdmin_Verify(t *testing.T) {
assert.False(t, verified)
req, err := http.NewRequest(http.MethodPut,
fmt.Sprintf("%s/api/v1/admin/verify/user1?site=remark42&verified=1", ts.URL), nil)
fmt.Sprintf("%s/api/v1/admin/verify/user1?site=remark42&verified=1", ts.URL), http.NoBody)
assert.NoError(t, err)
requireAdminOnly(t, req)
resp, err := sendReq(t, req, adminUmputunToken)
@@ -600,7 +600,7 @@ func TestAdmin_Verify(t *testing.T) {
assert.True(t, comments.Comments[0].User.Verified)
req, err = http.NewRequest(http.MethodPut,
fmt.Sprintf("%s/api/v1/admin/verify/user1?site=remark42&verified=0", ts.URL), nil)
fmt.Sprintf("%s/api/v1/admin/verify/user1?site=remark42&verified=0", ts.URL), http.NoBody)
assert.NoError(t, err)
resp, err = sendReq(t, req, adminUmputunToken)
require.NoError(t, err)
@@ -650,7 +650,7 @@ func TestAdmin_ExportFile(t *testing.T) {
addComment(t, c1, ts)
addComment(t, c2, ts)
req, err := http.NewRequest("GET", ts.URL+"/api/v1/admin/export?site=remark42&mode=file", nil)
req, err := http.NewRequest("GET", ts.URL+"/api/v1/admin/export?site=remark42&mode=file", http.NoBody)
require.NoError(t, err)
requireAdminOnly(t, req)
resp, err := sendReq(t, req, adminUmputunToken)
@@ -662,7 +662,7 @@ func TestAdmin_ExportFile(t *testing.T) {
ungzReader, err := gzip.NewReader(resp.Body)
assert.NoError(t, err)
assert.NoError(t, resp.Body.Close())
ungzBody, err := ioutil.ReadAll(ungzReader)
ungzBody, err := io.ReadAll(ungzReader)
assert.NoError(t, err)
assert.Equal(t, 3, strings.Count(string(ungzBody), "\n"))
assert.Equal(t, 2, strings.Count(string(ungzBody), "\"text\""))
@@ -713,14 +713,14 @@ func TestAdmin_DeleteMeRequest(t *testing.T) {
},
}
require.NoError(t, os.MkdirAll(os.TempDir()+"/ava-remark42/42", 0700))
require.NoError(t, ioutil.WriteFile(os.TempDir()+"/ava-remark42/42/pic.image", []byte("some image data"), 0600))
require.NoError(t, os.MkdirAll(os.TempDir()+"/ava-remark42/42", 0o700))
require.NoError(t, os.WriteFile(os.TempDir()+"/ava-remark42/42/pic.image", []byte("some image data"), 0o600))
tkn, err := srv.Authenticator.TokenService().Token(claims)
assert.NoError(t, err)
client := http.Client{}
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/v1/admin/deleteme?token=%s", ts.URL, tkn), nil)
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/v1/admin/deleteme?token=%s", ts.URL, tkn), http.NoBody)
assert.NoError(t, err)
req.SetBasicAuth("admin", "password")
@@ -754,7 +754,7 @@ func TestAdmin_DeleteMeRequestFailed(t *testing.T) {
// try with bad token
client := http.Client{}
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/v1/admin/deleteme?token=%s", ts.URL, "bad token"), nil)
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/v1/admin/deleteme?token=%s", ts.URL, "bad token"), http.NoBody)
assert.NoError(t, err)
req.SetBasicAuth("admin", "password")
resp, err := client.Do(req)
@@ -782,7 +782,7 @@ func TestAdmin_DeleteMeRequestFailed(t *testing.T) {
tkn, err := srv.Authenticator.TokenService().Token(claims)
assert.NoError(t, err)
req, err = http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/v1/admin/deleteme?token=%s", ts.URL, tkn), nil)
req, err = http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/v1/admin/deleteme?token=%s", ts.URL, tkn), http.NoBody)
assert.NoError(t, err)
req.SetBasicAuth("admin", "bad-password")
resp, err = client.Do(req)
@@ -795,7 +795,7 @@ func TestAdmin_DeleteMeRequestFailed(t *testing.T) {
badClaims.User.ID = "no-such-id"
tkn, err = srv.Authenticator.TokenService().Token(badClaims)
assert.NoError(t, err)
req, err = http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/v1/admin/deleteme?token=%s", ts.URL, tkn), nil)
req, err = http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/v1/admin/deleteme?token=%s", ts.URL, tkn), http.NoBody)
assert.NoError(t, err)
req.SetBasicAuth("admin", "password")
resp, err = client.Do(req)
@@ -808,13 +808,13 @@ func TestAdmin_DeleteMeRequestFailed(t *testing.T) {
badClaims2.User.SetBoolAttr("delete_me", false)
tkn, err = srv.Authenticator.TokenService().Token(badClaims2)
assert.NoError(t, err)
req, err = http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/v1/admin/deleteme?token=%s", ts.URL, tkn), nil)
req, err = http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/v1/admin/deleteme?token=%s", ts.URL, tkn), http.NoBody)
assert.NoError(t, err)
req.SetBasicAuth("admin", "password")
resp, err = client.Do(req)
assert.NoError(t, err)
assert.Equal(t, 403, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.NoError(t, resp.Body.Close())
assert.True(t, strings.Contains(string(b), "can't use provided token"))
+12 -13
View File
@@ -6,7 +6,6 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/http/httptest"
@@ -43,7 +42,7 @@ func TestMigrator_Import(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, http.StatusAccepted, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t, "{\"status\":\"import request accepted\"}\n", string(b))
assert.NoError(t, resp.Body.Close())
@@ -78,7 +77,7 @@ func TestMigrator_ImportForm(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, http.StatusAccepted, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t, "{\"status\":\"import request accepted\"}\n", string(b))
assert.NoError(t, resp.Body.Close())
@@ -101,7 +100,7 @@ func TestMigrator_ImportFromWP(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, http.StatusAccepted, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t, "{\"status\":\"import request accepted\"}\n", string(b))
assert.NoError(t, resp.Body.Close())
@@ -129,7 +128,7 @@ func TestMigrator_ImportFromCommento(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, http.StatusAccepted, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t, "{\"status\":\"import request accepted\"}\n", string(b))
assert.NoError(t, resp.Body.Close())
@@ -219,7 +218,7 @@ func TestMigrator_ImportWaitExpired(t *testing.T) {
assert.Equal(t, http.StatusAccepted, resp.StatusCode)
client = &http.Client{Timeout: 5 * time.Second}
req, err = http.NewRequest("GET", ts.URL+"/api/v1/admin/wait?site=remark42&timeout=5ms", nil)
req, err = http.NewRequest("GET", ts.URL+"/api/v1/admin/wait?site=remark42&timeout=5ms", http.NoBody)
require.NoError(t, err)
req.SetBasicAuth("admin", "password")
assert.NoError(t, err)
@@ -256,7 +255,7 @@ func TestMigrator_Export(t *testing.T) {
waitForMigrationCompletion(t, ts)
// check file mode
req, err = http.NewRequest("GET", ts.URL+"/api/v1/admin/export?mode=file&site=remark42", nil)
req, err = http.NewRequest("GET", ts.URL+"/api/v1/admin/export?mode=file&site=remark42", http.NoBody)
require.NoError(t, err)
req.SetBasicAuth("admin", "password")
resp, err = client.Do(req)
@@ -266,7 +265,7 @@ func TestMigrator_Export(t *testing.T) {
ungzReader, err := gzip.NewReader(resp.Body)
assert.NoError(t, err)
ungzBody, err := ioutil.ReadAll(ungzReader)
ungzBody, err := io.ReadAll(ungzReader)
assert.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.Equal(t, 3, strings.Count(string(ungzBody), "\n"))
@@ -274,7 +273,7 @@ func TestMigrator_Export(t *testing.T) {
t.Logf("%s", string(ungzBody))
// check stream mode
req, err = http.NewRequest("GET", ts.URL+"/api/v1/admin/export?mode=stream&site=remark42", nil)
req, err = http.NewRequest("GET", ts.URL+"/api/v1/admin/export?mode=stream&site=remark42", http.NoBody)
require.NoError(t, err)
req.SetBasicAuth("admin", "password")
resp, err = client.Do(req)
@@ -282,14 +281,14 @@ func TestMigrator_Export(t *testing.T) {
require.Equal(t, 200, resp.StatusCode)
require.Equal(t, "text/plain; charset=utf-8", resp.Header.Get("Content-Type"))
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.Equal(t, 3, strings.Count(string(body), "\n"))
assert.Equal(t, 2, strings.Count(string(body), "\"text\""))
t.Logf("%s", string(body))
req, err = http.NewRequest("GET", ts.URL+"/api/v1/admin/export?site=remark42", nil)
req, err = http.NewRequest("GET", ts.URL+"/api/v1/admin/export?site=remark42", http.NoBody)
require.NoError(t, err)
resp, err = client.Do(req)
require.NoError(t, err)
@@ -399,13 +398,13 @@ func TestMigrator_RemapReject(t *testing.T) {
func waitForMigrationCompletion(t *testing.T, ts *httptest.Server) {
client := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest("GET", ts.URL+"/api/v1/admin/wait?site=remark42", nil)
req, err := http.NewRequest("GET", ts.URL+"/api/v1/admin/wait?site=remark42", http.NoBody)
require.NoError(t, err)
req.SetBasicAuth("admin", "password")
resp, err := client.Do(req)
require.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, "{\"site_id\":\"remark42\",\"status\":\"completed\"}\n", string(b))
+67 -68
View File
@@ -9,7 +9,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
@@ -42,7 +41,7 @@ func TestRest_Create(t *testing.T) {
resp, err := post(t, ts.URL+"/api/v1/comment",
`{"text": "test 123", "locator":{"url": "https://radio-t.com/blah1", "site": "remark42"}}`)
assert.NoError(t, err)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
require.Equal(t, http.StatusCreated, resp.StatusCode, string(b))
assert.NoError(t, resp.Body.Close())
@@ -100,7 +99,7 @@ func TestRest_CreateTooBig(t *testing.T) {
resp, err := post(t, ts.URL+"/api/v1/comment", longComment)
assert.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.NoError(t, resp.Body.Close())
c := R.JSON{}
@@ -113,7 +112,7 @@ func TestRest_CreateTooBig(t *testing.T) {
resp, err = post(t, ts.URL+"/api/v1/comment", veryLongComment)
assert.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
b, err = ioutil.ReadAll(resp.Body)
b, err = io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.NoError(t, resp.Body.Close())
c = R.JSON{}
@@ -133,7 +132,7 @@ func TestRest_CreateWithRestrictedWord(t *testing.T) {
resp, err := post(t, ts.URL+"/api/v1/comment", badComment)
assert.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.NoError(t, resp.Body.Close())
c := R.JSON{}
@@ -174,7 +173,7 @@ func TestRest_CreateWithWrongImage(t *testing.T) {
resp, err := post(t, ts.URL+"/api/v1/comment", fmt.Sprintf(`{"text": "![non-existent.jpg](%s/api/v1/picture/dev_user/bad_picture)", "locator":{"url": "https://radio-t.com/blah1", "site": "radio-t"}}`, srv.RemarkURL))
assert.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.NoError(t, resp.Body.Close())
assert.Contains(t,
@@ -196,7 +195,7 @@ func TestRest_CreateWithLazyImage(t *testing.T) {
resp, err := post(t, ts.URL+"/api/v1/comment", body)
require.NoError(t, err)
require.Equal(t, http.StatusCreated, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.NoError(t, resp.Body.Close())
c := store.Comment{}
@@ -214,7 +213,7 @@ func TestRest_CreateAndGet(t *testing.T) {
`{"text": "**test** *123*\n\n http://radio-t.com", "locator":{"url": "https://radio-t.com/blah1", "site": "remark42"}}`)
require.NoError(t, err)
require.Equal(t, http.StatusCreated, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.NoError(t, resp.Body.Close())
c := R.JSON{}
@@ -259,7 +258,7 @@ func TestRest_Update(t *testing.T) {
req.Header.Add("X-JWT", devToken)
b, err := client.Do(req)
assert.NoError(t, err)
body, err := ioutil.ReadAll(b.Body)
body, err := io.ReadAll(b.Body)
assert.NoError(t, err)
assert.Equal(t, 200, b.StatusCode, string(body))
assert.NoError(t, b.Body.Close())
@@ -295,7 +294,7 @@ func TestRest_UpdateDelete(t *testing.T) {
resp, err := post(t, ts.URL+"/api/v1/counts?site=remark42", `["https://radio-t.com/blah1","https://radio-t.com/blah2"]`)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
bb, err := ioutil.ReadAll(resp.Body)
bb, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.NoError(t, resp.Body.Close())
j := []store.PostInfo{}
@@ -312,7 +311,7 @@ func TestRest_UpdateDelete(t *testing.T) {
req.Header.Add("X-JWT", devToken)
b, err := client.Do(req)
require.NoError(t, err)
body, err := ioutil.ReadAll(b.Body)
body, err := io.ReadAll(b.Body)
require.NoError(t, err)
assert.Equal(t, 200, b.StatusCode, string(body))
assert.NoError(t, b.Body.Close())
@@ -338,7 +337,7 @@ func TestRest_UpdateDelete(t *testing.T) {
resp, err = post(t, ts.URL+"/api/v1/counts?site=remark42", `["https://radio-t.com/blah1","https://radio-t.com/blah2"]`)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
bb, err = ioutil.ReadAll(resp.Body)
bb, err = io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.NoError(t, resp.Body.Close())
j = []store.PostInfo{}
@@ -364,7 +363,7 @@ func TestRest_UpdateNotOwner(t *testing.T) {
req.Header.Add("X-JWT", devToken)
b, err := client.Do(req)
assert.NoError(t, err)
body, err := ioutil.ReadAll(b.Body)
body, err := io.ReadAll(b.Body)
assert.NoError(t, err)
assert.NoError(t, b.Body.Close())
assert.Equal(t, 403, b.StatusCode, string(body), "update from non-owner")
@@ -415,7 +414,7 @@ func TestRest_UpdateWithRestrictedWords(t *testing.T) {
req.Header.Add("X-JWT", devToken)
b, err := client.Do(req)
assert.NoError(t, err)
body, err := ioutil.ReadAll(b.Body)
body, err := io.ReadAll(b.Body)
assert.NoError(t, err)
assert.NoError(t, b.Body.Close())
c := R.JSON{}
@@ -441,7 +440,7 @@ func TestRest_Vote(t *testing.T) {
vote := func(val int) int {
client := http.Client{}
req, err := http.NewRequest(http.MethodPut,
fmt.Sprintf("%s/api/v1/vote/%s?site=remark42&url=https://radio-t.com/blah&vote=%d", ts.URL, id1, val), nil)
fmt.Sprintf("%s/api/v1/vote/%s?site=remark42&url=https://radio-t.com/blah&vote=%d", ts.URL, id1, val), http.NoBody)
assert.NoError(t, err)
req.Header.Add("X-JWT", devToken)
resp, err := client.Do(req)
@@ -500,7 +499,7 @@ func TestRest_Vote(t *testing.T) {
assert.Equal(t, map[string]store.VotedIPInfo(nil), cr.VotedIPs, "hidden")
req, err := http.NewRequest("GET",
fmt.Sprintf("%s/api/v1/id/%s?site=remark42&url=https://radio-t.com/blah", ts.URL, id1), nil)
fmt.Sprintf("%s/api/v1/id/%s?site=remark42&url=https://radio-t.com/blah", ts.URL, id1), http.NoBody)
assert.NoError(t, err)
resp, err := sendReq(t, req, adminUmputunToken)
assert.NoError(t, err)
@@ -530,7 +529,7 @@ func TestRest_AnonVote(t *testing.T) {
vote := func(val int) int {
client := http.Client{}
req, err := http.NewRequest(http.MethodPut,
fmt.Sprintf("%s/api/v1/vote/%s?site=remark42&url=https://radio-t.com/blah&vote=%d", ts.URL, id1, val), nil)
fmt.Sprintf("%s/api/v1/vote/%s?site=remark42&url=https://radio-t.com/blah&vote=%d", ts.URL, id1, val), http.NoBody)
assert.NoError(t, err)
req.Header.Add("X-JWT", anonToken)
resp, err := client.Do(req)
@@ -541,13 +540,13 @@ func TestRest_AnonVote(t *testing.T) {
getWithAnonAuth := func(url string) (body string, code int) {
client := &http.Client{Timeout: 5 * time.Second}
req, err := http.NewRequest("GET", url, nil)
req, err := http.NewRequest("GET", url, http.NoBody)
require.NoError(t, err)
req.Header.Add("X-JWT", anonToken)
r, err := client.Do(req)
require.NoError(t, err)
defer r.Body.Close()
b, err := ioutil.ReadAll(r.Body)
b, err := io.ReadAll(r.Body)
assert.NoError(t, err)
return string(b), r.StatusCode
}
@@ -634,14 +633,14 @@ func TestRest_EmailAndTelegram(t *testing.T) {
for _, x := range testData {
x := x
t.Run(x.description, func(t *testing.T) {
req, err := http.NewRequest(x.method, ts.URL+x.url, nil)
req, err := http.NewRequest(x.method, ts.URL+x.url, http.NoBody)
require.NoError(t, err)
if !x.noAuth {
req.Header.Add("X-JWT", devToken)
}
resp, err := client.Do(req)
require.NoError(t, err)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.NoError(t, resp.Body.Close())
// read User.Email from the token in the cookie
@@ -677,7 +676,7 @@ func TestRest_EmailNotification(t *testing.T) {
req.Header.Add("X-JWT", devToken)
resp, err := client.Do(req)
assert.NoError(t, err)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusCreated, resp.StatusCode, string(body))
@@ -691,7 +690,7 @@ func TestRest_EmailNotification(t *testing.T) {
// create child comment from another user, email notification only to admin expected
req, err = http.NewRequest("POST", ts.URL+"/api/v1/comment", strings.NewReader(fmt.Sprintf(
`{"text": "test 456",
"pid": "%s",
"pid": %q,
"user": {"name": "other_user"},
"locator":{"url": "https://radio-t.com/blah1",
"site": "remark42"}}`, parentComment.ID)))
@@ -699,7 +698,7 @@ func TestRest_EmailNotification(t *testing.T) {
req.Header.Add("X-JWT", anonToken)
resp, err = client.Do(req)
assert.NoError(t, err)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusCreated, resp.StatusCode, string(body))
@@ -709,12 +708,12 @@ func TestRest_EmailNotification(t *testing.T) {
assert.Empty(t, mockDestination.Get()[1].Emails)
// send confirmation token for email
req, err = http.NewRequest(http.MethodPost, ts.URL+"/api/v1/email/subscribe?site=remark42&address=good@example.com", nil)
req, err = http.NewRequest(http.MethodPost, ts.URL+"/api/v1/email/subscribe?site=remark42&address=good@example.com", http.NoBody)
require.NoError(t, err)
req.Header.Add("X-JWT", devToken)
resp, err = client.Do(req)
require.NoError(t, err)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
@@ -725,23 +724,23 @@ func TestRest_EmailNotification(t *testing.T) {
verificationToken := mockDestination.GetVerify()[0].Token
// verify email
req, err = http.NewRequest(http.MethodPost, ts.URL+fmt.Sprintf("/api/v1/email/confirm?site=remark42&tkn=%s", verificationToken), nil)
req, err = http.NewRequest(http.MethodPost, ts.URL+fmt.Sprintf("/api/v1/email/confirm?site=remark42&tkn=%s", verificationToken), http.NoBody)
require.NoError(t, err)
req.Header.Add("X-JWT", devToken)
resp, err = client.Do(req)
require.NoError(t, err)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
// get user information to verify the subscription
req, err = http.NewRequest(http.MethodGet, ts.URL+"/api/v1/user?site=remark42", nil)
req, err = http.NewRequest(http.MethodGet, ts.URL+"/api/v1/user?site=remark42", http.NoBody)
require.NoError(t, err)
req.Header.Add("X-JWT", devToken)
resp, err = client.Do(req)
require.NoError(t, err)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
@@ -754,7 +753,7 @@ func TestRest_EmailNotification(t *testing.T) {
// create child comment from another user, email notification expected
req, err = http.NewRequest("POST", ts.URL+"/api/v1/comment", strings.NewReader(fmt.Sprintf(
`{"text": "test 789",
"pid": "%s",
"pid": %q,
"user": {"name": "other_user"},
"locator":{"url": "https://radio-t.com/blah1",
"site": "remark42"}}`, parentComment.ID)))
@@ -762,7 +761,7 @@ func TestRest_EmailNotification(t *testing.T) {
req.Header.Add("X-JWT", anonToken)
resp, err = client.Do(req)
assert.NoError(t, err)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusCreated, resp.StatusCode, string(body))
@@ -772,12 +771,12 @@ func TestRest_EmailNotification(t *testing.T) {
assert.Equal(t, []string{"good@example.com"}, mockDestination.Get()[2].Emails)
// delete user's email
req, err = http.NewRequest(http.MethodDelete, ts.URL+"/api/v1/email?site=remark42", nil)
req, err = http.NewRequest(http.MethodDelete, ts.URL+"/api/v1/email?site=remark42", http.NoBody)
require.NoError(t, err)
req.Header.Add("X-JWT", devToken)
resp, err = client.Do(req)
require.NoError(t, err)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.Equal(t, http.StatusOK, resp.StatusCode, string(body))
@@ -792,7 +791,7 @@ func TestRest_EmailNotification(t *testing.T) {
req.Header.Add("X-JWT", devToken)
resp, err = client.Do(req)
assert.NoError(t, err)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusCreated, resp.StatusCode, string(body))
@@ -822,7 +821,7 @@ func TestRest_TelegramNotification(t *testing.T) {
req.Header.Add("X-JWT", devToken)
resp, err := client.Do(req)
assert.NoError(t, err)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusCreated, resp.StatusCode, string(body))
@@ -836,7 +835,7 @@ func TestRest_TelegramNotification(t *testing.T) {
// create child comment from another user, telegram notification only to admin expected
req, err = http.NewRequest("POST", ts.URL+"/api/v1/comment", strings.NewReader(fmt.Sprintf(
`{"text": "test 456",
"pid": "%s",
"pid": %q,
"user": {"name": "other_user"},
"locator":{"url": "https://radio-t.com/blah1",
"site": "remark42"}}`, parentComment.ID)))
@@ -844,7 +843,7 @@ func TestRest_TelegramNotification(t *testing.T) {
req.Header.Add("X-JWT", anonToken)
resp, err = client.Do(req)
assert.NoError(t, err)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusCreated, resp.StatusCode, string(body))
@@ -854,12 +853,12 @@ func TestRest_TelegramNotification(t *testing.T) {
assert.Empty(t, mockDestination.Get()[1].Telegrams)
// subscribe to telegram while the telegram destination is absent
req, err = http.NewRequest(http.MethodGet, ts.URL+"/api/v1/telegram/subscribe?site=remark42", nil)
req, err = http.NewRequest(http.MethodGet, ts.URL+"/api/v1/telegram/subscribe?site=remark42", http.NoBody)
require.NoError(t, err)
req.Header.Add("X-JWT", devToken)
resp, err = client.Do(req)
require.NoError(t, err)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusInternalServerError, resp.StatusCode, string(body))
@@ -868,12 +867,12 @@ func TestRest_TelegramNotification(t *testing.T) {
mockTlgrm := &mockTelegram{notVerified: true, site: "unknown_site"}
srv.privRest.telegramService = mockTlgrm
// send confirmation token for telegram
req, err = http.NewRequest(http.MethodGet, ts.URL+"/api/v1/telegram/subscribe?site=remark42", nil)
req, err = http.NewRequest(http.MethodGet, ts.URL+"/api/v1/telegram/subscribe?site=remark42", http.NoBody)
require.NoError(t, err)
req.Header.Add("X-JWT", devToken)
resp, err = client.Do(req)
require.NoError(t, err)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
@@ -886,12 +885,12 @@ func TestRest_TelegramNotification(t *testing.T) {
assert.Equal(t, "botUsername", subscribeRequest.Bot)
// verify telegram, unsuccessfully because of not verified
req, err = http.NewRequest(http.MethodGet, ts.URL+fmt.Sprintf("/api/v1/telegram/subscribe?site=remark42&tkn=%s", subscribeRequest.Token), nil)
req, err = http.NewRequest(http.MethodGet, ts.URL+fmt.Sprintf("/api/v1/telegram/subscribe?site=remark42&tkn=%s", subscribeRequest.Token), http.NoBody)
require.NoError(t, err)
req.Header.Add("X-JWT", devToken)
resp, err = client.Do(req)
require.NoError(t, err)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusInternalServerError, resp.StatusCode, string(body))
@@ -900,12 +899,12 @@ func TestRest_TelegramNotification(t *testing.T) {
mockTlgrm.notVerified = false
// verify telegram, unsuccessfully because of unknown site
req, err = http.NewRequest(http.MethodGet, ts.URL+fmt.Sprintf("/api/v1/telegram/subscribe?site=remark42&tkn=%s", subscribeRequest.Token), nil)
req, err = http.NewRequest(http.MethodGet, ts.URL+fmt.Sprintf("/api/v1/telegram/subscribe?site=remark42&tkn=%s", subscribeRequest.Token), http.NoBody)
require.NoError(t, err)
req.Header.Add("X-JWT", devToken)
resp, err = client.Do(req)
require.NoError(t, err)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusBadRequest, resp.StatusCode, string(body))
@@ -913,12 +912,12 @@ func TestRest_TelegramNotification(t *testing.T) {
mockTlgrm.site = "remark42"
// verify telegram, successfully
req, err = http.NewRequest(http.MethodGet, ts.URL+fmt.Sprintf("/api/v1/telegram/subscribe?site=remark42&tkn=%s", subscribeRequest.Token), nil)
req, err = http.NewRequest(http.MethodGet, ts.URL+fmt.Sprintf("/api/v1/telegram/subscribe?site=remark42&tkn=%s", subscribeRequest.Token), http.NoBody)
require.NoError(t, err)
req.Header.Add("X-JWT", devToken)
resp, err = client.Do(req)
require.NoError(t, err)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
@@ -931,12 +930,12 @@ func TestRest_TelegramNotification(t *testing.T) {
assert.True(t, subscribeResult.Updated)
// get user information to verify the subscription
req, err = http.NewRequest(http.MethodGet, ts.URL+"/api/v1/user?site=remark42", nil)
req, err = http.NewRequest(http.MethodGet, ts.URL+"/api/v1/user?site=remark42", http.NoBody)
require.NoError(t, err)
req.Header.Add("X-JWT", devToken)
resp, err = client.Do(req)
require.NoError(t, err)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
@@ -949,7 +948,7 @@ func TestRest_TelegramNotification(t *testing.T) {
// create child comment from another user, telegram notification expected
req, err = http.NewRequest("POST", ts.URL+"/api/v1/comment", strings.NewReader(fmt.Sprintf(
`{"text": "test 789",
"pid": "%s",
"pid": %q,
"user": {"name": "other_user"},
"locator":{"url": "https://radio-t.com/blah1",
"site": "remark42"}}`, parentComment.ID)))
@@ -957,7 +956,7 @@ func TestRest_TelegramNotification(t *testing.T) {
req.Header.Add("X-JWT", anonToken)
resp, err = client.Do(req)
assert.NoError(t, err)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusCreated, resp.StatusCode, string(body))
@@ -967,12 +966,12 @@ func TestRest_TelegramNotification(t *testing.T) {
assert.Equal(t, []string{"good_telegram"}, mockDestination.Get()[2].Telegrams)
// delete user's telegram
req, err = http.NewRequest(http.MethodDelete, ts.URL+"/api/v1/telegram?site=remark42", nil)
req, err = http.NewRequest(http.MethodDelete, ts.URL+"/api/v1/telegram?site=remark42", http.NoBody)
require.NoError(t, err)
req.Header.Add("X-JWT", devToken)
resp, err = client.Do(req)
require.NoError(t, err)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.Equal(t, http.StatusOK, resp.StatusCode, string(body))
@@ -987,7 +986,7 @@ func TestRest_TelegramNotification(t *testing.T) {
req.Header.Add("X-JWT", devToken)
resp, err = client.Do(req)
assert.NoError(t, err)
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusCreated, resp.StatusCode, string(body))
@@ -1017,7 +1016,7 @@ func TestRest_UserAllData(t *testing.T) {
require.NoError(t, err)
client := &http.Client{Timeout: 1 * time.Second}
req, err := http.NewRequest("GET", ts.URL+"/api/v1/userdata?site=remark42", nil)
req, err := http.NewRequest("GET", ts.URL+"/api/v1/userdata?site=remark42", http.NoBody)
require.NoError(t, err)
req.Header.Add("X-JWT", devToken)
resp, err := client.Do(req)
@@ -1028,7 +1027,7 @@ func TestRest_UserAllData(t *testing.T) {
ungzReader, err := gzip.NewReader(resp.Body)
assert.NoError(t, err)
require.NoError(t, resp.Body.Close())
ungzBody, err := ioutil.ReadAll(ungzReader)
ungzBody, err := io.ReadAll(ungzReader)
assert.NoError(t, err)
strUungzBody := string(ungzBody)
assert.True(t, strings.HasPrefix(strUungzBody,
@@ -1046,7 +1045,7 @@ func TestRest_UserAllData(t *testing.T) {
Picture: "http://example.com/pic.png", IP: "127.0.0.1", SiteID: "remark42"}, parsed.Info)
assert.Equal(t, 3, len(parsed.Comments))
req, err = http.NewRequest("GET", ts.URL+"/api/v1/userdata?site=remark42", nil)
req, err = http.NewRequest("GET", ts.URL+"/api/v1/userdata?site=remark42", http.NoBody)
require.NoError(t, err)
resp, err = client.Do(req)
require.NoError(t, err)
@@ -1069,7 +1068,7 @@ func TestRest_UserAllDataManyComments(t *testing.T) {
require.NoError(t, err)
}
client := &http.Client{Timeout: 1 * time.Second}
req, err := http.NewRequest("GET", ts.URL+"/api/v1/userdata?site=remark42", nil)
req, err := http.NewRequest("GET", ts.URL+"/api/v1/userdata?site=remark42", http.NoBody)
require.NoError(t, err)
req.Header.Add("X-JWT", devToken)
resp, err := client.Do(req)
@@ -1080,7 +1079,7 @@ func TestRest_UserAllDataManyComments(t *testing.T) {
ungzReader, err := gzip.NewReader(resp.Body)
assert.NoError(t, err)
assert.NoError(t, resp.Body.Close())
ungzBody, err := ioutil.ReadAll(ungzReader)
ungzBody, err := io.ReadAll(ungzReader)
assert.NoError(t, err)
strUngzBody := string(ungzBody)
assert.True(t, strings.HasPrefix(strUngzBody,
@@ -1093,13 +1092,13 @@ func TestRest_DeleteMe(t *testing.T) {
defer teardown()
client := http.Client{}
req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/deleteme?site=remark42", ts.URL), nil)
req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/deleteme?site=remark42", ts.URL), http.NoBody)
assert.NoError(t, err)
req.Header.Add("X-JWT", devToken)
resp, err := client.Do(req)
assert.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
assert.NoError(t, resp.Body.Close())
assert.NoError(t, err)
@@ -1115,7 +1114,7 @@ func TestRest_DeleteMe(t *testing.T) {
assert.Equal(t, "dev", claims.User.ID)
assert.Equal(t, "https://demo.remark42.com/web/deleteme.html?token="+tkn, m["link"])
req, err = http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/deleteme?site=remark42", ts.URL), nil)
req, err = http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/deleteme?site=remark42", ts.URL), http.NoBody)
assert.NoError(t, err)
resp, err = client.Do(req)
assert.NoError(t, err)
@@ -1146,7 +1145,7 @@ func TestRest_SavePictureCtrl(t *testing.T) {
resp, err := client.Do(req)
assert.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
@@ -1161,7 +1160,7 @@ func TestRest_SavePictureCtrl(t *testing.T) {
resp, err := http.Get(fmt.Sprintf("%s/api/v1/picture/%s", ts.URL, id))
require.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.Equal(t, 1462, len(body))
@@ -1238,7 +1237,7 @@ func TestRest_CreateWithPictures(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.NoError(t, resp.Body.Close())
m := map[string]string{}
@@ -1254,11 +1253,11 @@ func TestRest_CreateWithPictures(t *testing.T) {
}
text := fmt.Sprintf(`text 123 ![](%s/api/v1/picture/%s) *xxx* ![](%s/api/v1/picture/%s) ![](%s/api/v1/picture/%s)`, svc.RemarkURL, ids[0], svc.RemarkURL, ids[1], svc.RemarkURL, ids[2])
body := fmt.Sprintf(`{"text": "%s", "locator":{"url": "https://radio-t.com/blah1", "site": "remark42"}}`, text)
body := fmt.Sprintf(`{"text": %q, "locator":{"url": "https://radio-t.com/blah1", "site": "remark42"}}`, text)
resp, err := post(t, ts.URL+"/api/v1/comment", body)
assert.NoError(t, err)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusCreated, resp.StatusCode, string(b))
+2 -2
View File
@@ -5,8 +5,8 @@ import (
"crypto/sha1" // nolint
"encoding/base64"
"io"
"io/ioutil"
"net/http"
"os"
"path"
"strconv"
"strings"
@@ -346,7 +346,7 @@ func (s *public) loadPictureCtrl(w http.ResponseWriter, r *http.Request) {
// GET /index.html - respond to /index.html with the content of getstarted.html under /web root
func (s *public) getStartedCtrl(w http.ResponseWriter, r *http.Request) {
data, err := ioutil.ReadFile(path.Join(s.webRoot, "getstarted.html"))
data, err := os.ReadFile(path.Join(s.webRoot, "getstarted.html"))
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
+10 -10
View File
@@ -3,7 +3,7 @@ package api
import (
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"strings"
"testing"
@@ -34,7 +34,7 @@ func TestRest_Preview(t *testing.T) {
resp, err := post(t, ts.URL+"/api/v1/preview", `{"text": "test 123", "locator":{"url": "https://radio-t.com/blah1", "site": "radio-t"}}`)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.NoError(t, resp.Body.Close())
assert.Equal(t, "<p>test 123</p>\n", string(b))
@@ -47,7 +47,7 @@ func TestRest_Preview(t *testing.T) {
resp, err = post(t, ts.URL+"/api/v1/preview", fmt.Sprintf(`{"text": "![non-existent.jpg](%s/api/v1/picture/dev_user/bad_picture)", "locator":{"url": "https://radio-t.com/blah1", "site": "radio-t"}}`, srv.RemarkURL))
assert.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
b, err = ioutil.ReadAll(resp.Body)
b, err = io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.NoError(t, resp.Body.Close())
assert.Contains(t,
@@ -69,7 +69,7 @@ func TestRest_PreviewWithWrongImage(t *testing.T) {
resp, err := post(t, ts.URL+"/api/v1/preview", fmt.Sprintf(`{"text": "![non-existent.jpg](%s/api/v1/picture/dev_user/bad_picture)", "locator":{"url": "https://radio-t.com/blah1", "site": "radio-t"}}`, srv.RemarkURL))
assert.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.NoError(t, resp.Body.Close())
assert.Contains(t,
@@ -98,13 +98,13 @@ srv, ts := prep(t)
BKT
`
text = strings.Replace(text, "BKT", "```", -1)
j := fmt.Sprintf(`{"text": "%s", "locator":{"url": "https://radio-t.com/blah1", "site": "radio-t"}}`, text)
j := fmt.Sprintf(`{"text": %q, "locator":{"url": "https://radio-t.com/blah1", "site": "radio-t"}}`, text)
j = strings.Replace(j, "\n", "\\n", -1)
resp, err := post(t, ts.URL+"/api/v1/preview", j)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t,
`<h1>h1</h1>
@@ -126,13 +126,13 @@ func main(aa string) int {return 0}
BKT
`
text = strings.Replace(text, "BKT", "```", -1)
j := fmt.Sprintf(`{"text": "%s", "locator":{"url": "https://radio-t.com/blah1", "site": "radio-t"}}`, text)
j := fmt.Sprintf(`{"text": %q, "locator":{"url": "https://radio-t.com/blah1", "site": "radio-t"}}`, text)
j = strings.Replace(j, "\n", "\\n", -1)
resp, err := post(t, ts.URL+"/api/v1/preview", j)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t, `<pre class="chroma"><span class="kd">func</span> <span class="nf">main</span><span class="p">(</span><span class="nx">aa</span> <span class="kt">string</span><span class="p">)</span> <span class="kt">int</span> <span class="p">{</span><span class="k">return</span> <span class="mi">0</span><span class="p">}</span>
</pre>`, string(b))
@@ -247,7 +247,7 @@ func TestRest_FindReadOnly(t *testing.T) {
// set post to read-only
client := http.Client{}
req, err := http.NewRequest(http.MethodPut,
fmt.Sprintf("%s/api/v1/admin/readonly?site=remark42&url=https://radio-t.com/blah1&ro=1", ts.URL), nil)
fmt.Sprintf("%s/api/v1/admin/readonly?site=remark42&url=https://radio-t.com/blah1&ro=1", ts.URL), http.NoBody)
assert.NoError(t, err)
req.SetBasicAuth("admin", "password")
resp, err := client.Do(req)
@@ -517,7 +517,7 @@ func TestRest_Counts(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.NoError(t, resp.Body.Close())
+12 -12
View File
@@ -6,7 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"io"
"math/rand"
"net"
"net/http"
@@ -52,7 +52,7 @@ func TestRest_FileServer(t *testing.T) {
testHTMLName := "test-remark.html"
testHTMLFile := os.TempDir() + "/" + testHTMLName
err := ioutil.WriteFile(testHTMLFile, []byte("some html"), 0700)
err := os.WriteFile(testHTMLFile, []byte("some html"), 0o700)
assert.NoError(t, err)
body, code := get(t, ts.URL+"/web/"+testHTMLName)
@@ -66,7 +66,7 @@ func TestRest_GetStarted(t *testing.T) {
defer teardown()
getStartedHTML := os.TempDir() + "/getstarted.html"
err := ioutil.WriteFile(getStartedHTML, []byte("some html blah"), 0700)
err := os.WriteFile(getStartedHTML, []byte("some html blah"), 0o700)
assert.NoError(t, err)
body, code := get(t, ts.URL+"/index.html")
@@ -159,7 +159,7 @@ func TestRest_RunStaticSSLMode(t *testing.T) {
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, 200, resp.StatusCode)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t, "pong", string(body))
@@ -239,7 +239,7 @@ func Test_URLKey(t *testing.T) {
for i, tt := range tbl {
tt := tt
t.Run(strconv.Itoa(i), func(t *testing.T) {
r, err := http.NewRequest("GET", tt.url, nil)
r, err := http.NewRequest("GET", tt.url, http.NoBody)
require.NoError(t, err)
if tt.user.ID != "" {
r = rest.SetUserInfo(r, tt.user)
@@ -265,7 +265,7 @@ func Test_URLKeyWithUser(t *testing.T) {
for i, tt := range tbl {
tt := tt
t.Run(strconv.Itoa(i), func(t *testing.T) {
r, err := http.NewRequest("GET", tt.url, nil)
r, err := http.NewRequest("GET", tt.url, http.NoBody)
require.NoError(t, err)
if tt.user.ID != "" {
r = rest.SetUserInfo(r, tt.user)
@@ -507,7 +507,7 @@ func fakeAuth(next http.Handler) http.Handler {
func get(t *testing.T, url string) (response string, statusCode int) {
r, err := http.Get(url)
require.NoError(t, err)
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
require.NoError(t, r.Body.Close())
return string(body), r.StatusCode
@@ -523,12 +523,12 @@ func sendReq(_ *testing.T, r *http.Request, tkn string) (*http.Response, error)
func getWithDevAuth(t *testing.T, url string) (body string, code int) {
client := &http.Client{Timeout: 5 * time.Second}
req, err := http.NewRequest("GET", url, nil)
req, err := http.NewRequest("GET", url, http.NoBody)
require.NoError(t, err)
req.Header.Add("X-JWT", devToken)
r, err := client.Do(req)
require.NoError(t, err)
b, err := ioutil.ReadAll(r.Body)
b, err := io.ReadAll(r.Body)
assert.NoError(t, err)
require.NoError(t, r.Body.Close())
return string(b), r.StatusCode
@@ -536,12 +536,12 @@ func getWithDevAuth(t *testing.T, url string) (body string, code int) {
func getWithAdminAuth(t *testing.T, url string) (response string, statusCode int) {
client := &http.Client{Timeout: 5 * time.Second}
req, err := http.NewRequest("GET", url, nil)
req, err := http.NewRequest("GET", url, http.NoBody)
require.NoError(t, err)
req.SetBasicAuth("admin", "password")
r, err := client.Do(req)
require.NoError(t, err)
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
assert.NoError(t, err)
require.NoError(t, r.Body.Close())
return string(body), r.StatusCode
@@ -565,7 +565,7 @@ func addComment(t *testing.T, c store.Comment, ts *httptest.Server) string {
resp, err := client.Do(req)
require.NoError(t, err)
require.Equal(t, http.StatusCreated, resp.StatusCode)
b, err = ioutil.ReadAll(resp.Body)
b, err = io.ReadAll(resp.Body)
require.NoError(t, resp.Body.Close())
require.NoError(t, err)
+3 -3
View File
@@ -3,7 +3,7 @@ package api
import (
"context"
"crypto/tls"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"os"
@@ -68,7 +68,7 @@ func TestSSL_ACME_HTTPChallengeRouter(t *testing.T) {
assert.Equal(t, "https://localhost:443/blah?param=1", resp.Header.Get("Location"))
// check acme http challenge
req, err := http.NewRequest("GET", ts.URL+"/.well-known/acme-challenge/token123", nil)
req, err := http.NewRequest("GET", ts.URL+"/.well-known/acme-challenge/token123", http.NoBody)
require.NoError(t, err)
req.Host = "localhost" // for passing hostPolicy check
resp, err = client.Do(req)
@@ -83,7 +83,7 @@ func TestSSL_ACME_HTTPChallengeRouter(t *testing.T) {
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, 200, resp.StatusCode)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, "token", string(body))
}
+5 -5
View File
@@ -3,7 +3,7 @@ package rest
import (
"errors"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"testing"
@@ -31,7 +31,7 @@ func TestSendErrorJSON(t *testing.T) {
require.NoError(t, err)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, 500, resp.StatusCode)
@@ -61,7 +61,7 @@ func TestSendErrorHTML(t *testing.T) {
require.NoError(t, err)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, 500, resp.StatusCode)
@@ -72,7 +72,7 @@ func TestSendErrorHTML(t *testing.T) {
func TestErrorDetailsMsg(t *testing.T) {
callerFn := func() {
req, err := http.NewRequest("GET", "https://example.com/test?k1=v1&k2=v2", nil)
req, err := http.NewRequest("GET", "https://example.com/test?k1=v1&k2=v2", http.NoBody)
require.NoError(t, err)
req.RemoteAddr = "1.2.3.4"
msg := errDetailsMsg(req, 500, errors.New("error 500"), "error details 123456", 123)
@@ -85,7 +85,7 @@ func TestErrorDetailsMsg(t *testing.T) {
func TestErrorDetailsMsgWithUser(t *testing.T) {
callerFn := func() {
req, err := http.NewRequest("GET", "https://example.com/test?k1=v1&k2=v2", nil)
req, err := http.NewRequest("GET", "https://example.com/test?k1=v1&k2=v2", http.NoBody)
require.NoError(t, err)
req.RemoteAddr = "127.0.0.1:1234"
req = SetUserInfo(req, store.User{Name: "test", ID: "id"})
+2 -3
View File
@@ -5,7 +5,6 @@ import (
"context"
"encoding/base64"
"io"
"io/ioutil"
"net/http"
"strings"
"time"
@@ -149,7 +148,7 @@ func (p Image) downloadImage(ctx context.Context, imgURL string) ([]byte, error)
var resp *http.Response
err := repeater.NewDefault(5, time.Second).Do(ctx, func() error {
var e error
req, e := http.NewRequest("GET", imgURL, nil)
req, e := http.NewRequest("GET", imgURL, http.NoBody)
if e != nil {
return errors.Wrapf(e, "failed to make request for %s", imgURL)
}
@@ -165,7 +164,7 @@ func (p Image) downloadImage(ctx context.Context, imgURL string) ([]byte, error)
return nil, errors.Errorf("got unsuccessful response status %d while fetching %s", resp.StatusCode, imgURL)
}
imgData, err := ioutil.ReadAll(resp.Body)
imgData, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.Errorf("unable to read image body")
}
+2 -3
View File
@@ -4,7 +4,6 @@ import (
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"strconv"
@@ -42,7 +41,7 @@ const gopher = "iVBORw0KGgoAAAANSUhEUgAAAEsAAAA8CAAAAAALAhhPAAAFfUlEQVRYw62XeWwU
func gopherPNG() io.Reader { return base64.NewDecoder(base64.StdEncoding, strings.NewReader(gopher)) }
func gopherPNGBytes() []byte {
img, _ := ioutil.ReadAll(gopherPNG())
img, _ := io.ReadAll(gopherPNG())
return img
}
@@ -246,7 +245,7 @@ func TestImage_RoutesTimedOut(t *testing.T) {
resp, err := http.Get(ts.URL + "/?src=" + encodedImgURL)
require.NoError(t, err)
assert.Equal(t, http.StatusNotFound, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
assert.NoError(t, resp.Body.Close())
require.NoError(t, err)
t.Log(string(b))
+2 -2
View File
@@ -10,7 +10,7 @@ import (
)
func TestUser_GetUserInfo(t *testing.T) {
r, err := http.NewRequest("GET", "http://blah.com", nil)
r, err := http.NewRequest("GET", "http://blah.com", http.NoBody)
assert.NoError(t, err)
_, err = GetUserInfo(r)
assert.Error(t, err, "no user info")
@@ -28,7 +28,7 @@ func TestUser_MustGetUserInfo(t *testing.T) {
}
}()
r, err := http.NewRequest("GET", "http://blah.com", nil)
r, err := http.NewRequest("GET", "http://blah.com", http.NoBody)
assert.NoError(t, err)
_ = MustGetUserInfo(r)
assert.Fail(t, "should panic")
+2 -2
View File
@@ -8,7 +8,7 @@ package admin
import (
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"testing"
@@ -92,7 +92,7 @@ func TestRemote_OnEvent(t *testing.T) {
func testServer(t *testing.T, req, resp string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
assert.Equal(t, req, string(body))
t.Logf("req: %s", string(body))
+1 -1
View File
@@ -159,7 +159,7 @@ var reHref = regexp.MustCompile(`<a\s+(?:[^>]*?\s+)?href="([^"]*)"`)
// SanitizeAsURL drops dangerous code from a url.
// It wraps input with href to trigger bluemonday sanitizer and cleans href after sanitizing done
func (c *Comment) SanitizeAsURL(inp string) string {
h := fmt.Sprintf(`<a href="%s">`, inp)
h := fmt.Sprintf(`<a href=%q>`, inp)
clean := bluemonday.UGCPolicy().Sanitize(h)
if match := reHref.FindStringSubmatch(clean); len(match) > 1 {
return match[1]
+1 -1
View File
@@ -55,7 +55,7 @@ func NewBoltDB(options bolt.Options, sites ...BoltSite) (*BoltDB, error) {
log.Printf("[INFO] bolt store for sites %+v, options %+v", sites, options)
result := BoltDB{dbs: make(map[string]*bolt.DB)}
for _, site := range sites {
db, err := bolt.Open(site.FileName, 0600, &options) //nolint:gocritic //octalLiteral is OK as FileMode
db, err := bolt.Open(site.FileName, 0o600, &options) //nolint:gocritic //octalLiteral is OK as FileMode
if err != nil {
return nil, errors.Wrapf(err, "failed to make boltdb for %s", site.FileName)
}
+3 -3
View File
@@ -2,7 +2,7 @@ package engine
import (
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"testing"
@@ -74,7 +74,7 @@ func TestRemote_GetWithErrorRemote(t *testing.T) {
func TestRemote_FailedStatus(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
t.Logf("req: %s", string(body))
w.WriteHeader(400)
@@ -190,7 +190,7 @@ func TestRemote_Close(t *testing.T) {
func testServer(t *testing.T, req, resp string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
assert.Equal(t, req, string(body))
t.Logf("req: %s", string(body))
+1 -1
View File
@@ -25,7 +25,7 @@ type Bolt struct {
// NewBoltStorage create bolt image store
func NewBoltStorage(fileName string, options bolt.Options) (*Bolt, error) {
db, err := bolt.Open(fileName, 0600, &options) //nolint:gocritic //octalLiteral is OK as FileMode
db, err := bolt.Open(fileName, 0o600, &options) //nolint:gocritic //octalLiteral is OK as FileMode
if err != nil {
return nil, errors.Wrapf(err, "failed to make boltdb for %s", fileName)
}
+5 -5
View File
@@ -4,7 +4,7 @@ import (
"context"
"fmt"
"hash/crc64"
"io/ioutil"
"io"
"math"
"os"
"path"
@@ -37,11 +37,11 @@ type FileSystem struct {
func (f *FileSystem) Save(id string, img []byte) error {
dst := f.location(f.Staging, id)
if err := os.MkdirAll(path.Dir(dst), 0700); err != nil {
if err := os.MkdirAll(path.Dir(dst), 0o700); err != nil {
return errors.Wrap(err, "can't make image directory")
}
if err := ioutil.WriteFile(dst, img, 0600); err != nil {
if err := os.WriteFile(dst, img, 0o600); err != nil {
return errors.Wrapf(err, "can't write image file with id %s", id)
}
@@ -54,7 +54,7 @@ func (f *FileSystem) Commit(id string) error {
log.Printf("[DEBUG] Commit image %s", id)
stagingImage, permImage := f.location(f.Staging, id), f.location(f.Location, id)
if err := os.MkdirAll(path.Dir(permImage), 0700); err != nil {
if err := os.MkdirAll(path.Dir(permImage), 0o700); err != nil {
return errors.Wrap(err, "can't make image directory")
}
@@ -99,7 +99,7 @@ func (f *FileSystem) Load(id string) ([]byte, error) {
if err != nil {
return nil, errors.Wrapf(err, "can't load image %s", id)
}
return ioutil.ReadAll(fh)
return io.ReadAll(fh)
}
// Cleanup runs scan of staging and removes old files based on ttl
+6 -6
View File
@@ -40,7 +40,7 @@ const gopher = "iVBORw0KGgoAAAANSUhEUgAAAEsAAAA8CAAAAAALAhhPAAAFfUlEQVRYw62XeWwU
func gopherPNG() io.Reader { return base64.NewDecoder(base64.StdEncoding, strings.NewReader(gopher)) }
func gopherPNGBytes() []byte {
img, _ := ioutil.ReadAll(gopherPNG())
img, _ := io.ReadAll(gopherPNG())
return img
}
@@ -53,7 +53,7 @@ func TestFsStore_Save(t *testing.T) {
assert.NoError(t, err)
img := svc.location(svc.Staging, id)
data, err := ioutil.ReadFile(img)
data, err := os.ReadFile(img)
assert.NoError(t, err)
assert.Equal(t, 1462, len(data))
}
@@ -65,7 +65,7 @@ func TestFsStore_SaveNoResizeJpeg(t *testing.T) {
fh, err := os.Open("testdata/circles.jpg")
defer func() { assert.NoError(t, fh.Close()) }()
assert.NoError(t, err)
img, err := ioutil.ReadAll(fh)
img, err := io.ReadAll(fh)
assert.NoError(t, err)
id := "test_img"
err = svc.Save(id, img)
@@ -73,7 +73,7 @@ func TestFsStore_SaveNoResizeJpeg(t *testing.T) {
imgPath := svc.location(svc.Staging, id)
t.Log(imgPath)
data, err := ioutil.ReadFile(imgPath)
data, err := os.ReadFile(imgPath)
assert.NoError(t, err)
assert.Equal(t, 23983, len(data))
}
@@ -94,7 +94,7 @@ func TestFsStore_SaveAndCommit(t *testing.T) {
img := svc.location(svc.Location, id)
t.Log(img)
data, err := ioutil.ReadFile(img)
data, err := os.ReadFile(img)
assert.NoError(t, err)
assert.Equal(t, 1462, len(data))
}
@@ -188,7 +188,7 @@ func TestFsStore_Cleanup(t *testing.T) {
err := svc.Save(id, gopherPNGBytes())
require.NoError(t, err)
img := svc.location(svc.Staging, id)
data, err := ioutil.ReadFile(img)
data, err := os.ReadFile(img)
require.NoError(t, err)
assert.Equal(t, 1462, len(data))
return img
+1 -2
View File
@@ -17,7 +17,6 @@ import (
_ "image/jpeg"
"image/png"
"io"
"io/ioutil"
"net/http"
"net/url"
"path"
@@ -341,7 +340,7 @@ func readAndValidateImage(r io.Reader, maxSize int) ([]byte, error) {
}
lr := io.LimitReader(r, int64(maxSize)+1)
data, err := ioutil.ReadAll(lr)
data, err := io.ReadAll(lr)
if err != nil {
return nil, err
}
+2 -3
View File
@@ -7,7 +7,6 @@ import (
"fmt"
"image"
"io"
"io/ioutil"
"os"
"strconv"
"strings"
@@ -122,7 +121,7 @@ func TestService_Cleanup(t *testing.T) {
svc := NewService(&store, ServiceParams{EditDuration: 20 * time.Millisecond})
// cancel context after 2.1 cleanup TTLs
ctx, cancel := context.WithTimeout(context.Background(), svc.EditDuration / 100 * 15 * 21)
ctx, cancel := context.WithTimeout(context.Background(), svc.EditDuration/100*15*21)
defer cancel()
svc.Cleanup(ctx)
store.AssertNumberOfCalls(t, "Cleanup", 2)
@@ -209,7 +208,7 @@ func TestService_resize(t *testing.T) {
}
for _, c := range cases {
img, err := ioutil.ReadFile(c.file)
img, err := os.ReadFile(c.file)
require.NoError(t, err, "can't open test file %s", c.file)
// no need for resize, image dimensions are smaller than resize limit
+2 -2
View File
@@ -4,7 +4,7 @@ import (
"context"
"encoding/base64"
"encoding/json"
"io/ioutil"
"io"
"strings"
"time"
@@ -38,7 +38,7 @@ func (r *RPC) Load(id string) ([]byte, error) {
if err := json.Unmarshal(*resp.Result, &rawImg); err != nil {
return nil, err
}
return ioutil.ReadAll(base64.NewDecoder(base64.StdEncoding, strings.NewReader(rawImg)))
return io.ReadAll(base64.NewDecoder(base64.StdEncoding, strings.NewReader(rawImg)))
}
// Commit file stored in staging location by moving it to permanent location
+3 -3
View File
@@ -3,7 +3,7 @@ package image
import (
"context"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"testing"
@@ -15,7 +15,7 @@ import (
)
func TestRemote_SaveWithID(t *testing.T) {
ts := testServer(t, fmt.Sprintf(`{"method":"image.save_with_id","params":["54321","%s"],"id":1}`, gopher),
ts := testServer(t, fmt.Sprintf(`{"method":"image.save_with_id","params":["54321",%q],"id":1}`, gopher),
`{"id":1}`)
defer ts.Close()
c := RPC{Client: jrpc.Client{API: ts.URL, Client: http.Client{}}}
@@ -93,7 +93,7 @@ func TestRemote_Info(t *testing.T) {
func testServer(t *testing.T, req, resp string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
assert.Equal(t, req, string(body))
_, _ = fmt.Fprint(w, resp)
+1 -1
View File
@@ -113,7 +113,7 @@ func TestService_CreateFromPartialWithTitle(t *testing.T) {
postTitle := "Post Title 42"
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.String() == postPath {
_, err := w.Write([]byte(fmt.Sprintf("<html><title>%s</title><body>...</body></html>", postTitle)))
_, err := fmt.Fprintf(w, "<html><title>%s</title><body>...</body></html>", postTitle)
assert.NoError(t, err)
return
}
+1 -1
View File
@@ -82,7 +82,7 @@ func TestTitle_GetConcurrent(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.String(), "/good") {
atomic.AddInt32(&hits, 1)
_, err := w.Write([]byte(fmt.Sprintf("<html><title>blah 123 %s</title><body>%s</body></html>", r.URL.String(), body)))
_, err := fmt.Fprintf(w, "<html><title>blah 123 %s</title><body>%s</body></html>", r.URL.String(), body)
assert.NoError(t, err)
return
}
+3 -3
View File
@@ -2,7 +2,7 @@ package service
import (
"encoding/json"
"io/ioutil"
"os"
"testing"
"time"
@@ -160,7 +160,7 @@ func TestTreeSortNodes(t *testing.T) {
func BenchmarkTree(b *testing.B) {
comments := []store.Comment{}
data, err := ioutil.ReadFile("testdata/tree_bench.json")
data, err := os.ReadFile("testdata/tree_bench.json")
assert.NoError(b, err)
err = json.Unmarshal(data, &comments)
assert.NoError(b, err)
@@ -173,7 +173,7 @@ func BenchmarkTree(b *testing.B) {
// loadJsonFile read fixtrue file and clear any custom json formatting
func mustLoadJSONFile(t *testing.T, file string) []byte {
expJSON, err := ioutil.ReadFile(file)
expJSON, err := os.ReadFile(file)
require.NoError(t, err)
expTree := Tree{}
err = json.Unmarshal(expJSON, &expTree)
+2 -2
View File
@@ -1,8 +1,8 @@
package templates
import (
"io/ioutil"
"net/http"
"os"
"path/filepath"
log "github.com/go-pkgz/lgr"
@@ -34,5 +34,5 @@ func (f *FS) ReadFile(path string) ([]byte, error) {
if f.statik != nil {
return fs.ReadFile(f.statik, filepath.Join("/", path)) //nolint:gocritic // root folder is a requirement for statik
}
return ioutil.ReadFile(filepath.Clean(path))
return os.ReadFile(filepath.Clean(path))
}