Skip to content
This repository has been archived by the owner on Dec 26, 2019. It is now read-only.

Commit

Permalink
improve code from outputs of golangci-lint
Browse files Browse the repository at this point in the history
  • Loading branch information
PatWie committed May 5, 2019
1 parent 9c8e29b commit d5e5031
Show file tree
Hide file tree
Showing 34 changed files with 118 additions and 126 deletions.
4 changes: 1 addition & 3 deletions .drone.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,7 @@ steps:
commands:
- cp .infomark.yml.ci .infomark.yml
- export INFOMARK_CONFIG_DIR=`pwd`
-
- go test ./api/app -cover -v --goblin.timeout 15s
- go test ./api/helper -cover -v
- go test ./... -cover -v --goblin.timeout 15s
environment:
GOPROXY: https://gomods.patwie.com/

Expand Down
4 changes: 4 additions & 0 deletions api/app/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,10 @@ func (rs *AccountResource) GetEnrollmentsHandler(w http.ResponseWriter, r *http.

// get enrollments
enrollments, err := rs.Stores.User.GetEnrollments(accessClaims.LoginID)
if err != nil {
render.Render(w, r, ErrInternalServerErrorWithDetails(err))
return
}

// render JSON reponse
if err = render.RenderList(w, r, rs.newUserEnrollmentsResponse(enrollments)); err != nil {
Expand Down
6 changes: 3 additions & 3 deletions api/app/account_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -302,8 +302,8 @@ func TestAccount(t *testing.T) {
g.Assert(err).Equal(nil)
g.Assert(w.Code).Equal(http.StatusOK)

if !strings.HasSuffix(w.HeaderMap["Content-Type"][0], "jpeg") {
g.Assert(strings.HasSuffix(w.HeaderMap["Content-Type"][0], "jpg")).Equal(true)
if !strings.HasSuffix(w.Header().Get("Content-Type"), "jpeg") {
g.Assert(strings.HasSuffix(w.Header().Get("Content-Type"), "jpg")).Equal(true)
}

})
Expand Down Expand Up @@ -344,7 +344,7 @@ func TestAccount(t *testing.T) {
w = tape.GetWithClaims("/api/v1/account/avatar", 1, true)
g.Assert(err).Equal(nil)
g.Assert(w.Code).Equal(http.StatusOK)
g.Assert(strings.HasSuffix(w.HeaderMap["Content-Type"][0], "png")).Equal(true)
g.Assert(strings.HasSuffix(w.Header().Get("Content-Type"), "png")).Equal(true)

})

Expand Down
7 changes: 0 additions & 7 deletions api/app/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,6 @@ import (
"github.com/jmoiron/sqlx"
)

type ctxKey int

const (
ctxAccount ctxKey = iota
ctxProfile
)

// UserStore defines user related database queries
type UserStore interface {
Get(userID int64) (*model.User, error)
Expand Down
4 changes: 4 additions & 0 deletions api/app/course.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ func NewCourseResource(stores *Stores) *CourseResource {
func (rs *CourseResource) IndexHandler(w http.ResponseWriter, r *http.Request) {
// fetch collection of courses from database
courses, err := rs.Stores.Course.GetAll()
if err != nil {
render.Render(w, r, ErrInternalServerErrorWithDetails(err))
return
}

// render JSON reponse
if err = render.RenderList(w, r, rs.newCourseListResponse(courses)); err != nil {
Expand Down
2 changes: 2 additions & 0 deletions api/app/course_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ func TestCourse(t *testing.T) {
enrollmentsExpected, err := stores.Course.FindEnrolledUsers(courseActive.ID,
[]string{"0", "1", "2"}, "%chi%",
)
g.Assert(err).Equal(nil)

w := tape.GetWithClaims("/api/v1/courses/1/enrollments?q=chi", 1, false)
enrollmentsActual := []enrollmentResponse{}
Expand Down Expand Up @@ -264,6 +265,7 @@ func TestCourse(t *testing.T) {
// verify body
courseReturn := &courseResponse{}
err = json.NewDecoder(w.Body).Decode(&courseReturn)
g.Assert(err).Equal(nil)
g.Assert(courseReturn.Name).Equal(entrySent.Name)
g.Assert(courseReturn.Description).Equal(entrySent.Description)
g.Assert(courseReturn.BeginsAt.Equal(entrySent.BeginsAt)).Equal(true)
Expand Down
5 changes: 2 additions & 3 deletions api/app/grade_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -496,16 +496,15 @@ func TestGrade(t *testing.T) {
PublicDockerImage: null.StringFrom("ff"),
PrivateDockerImage: null.StringFrom("ff"),
}, sheet1.ID)
g.Assert(err).Equal(nil)

task2, err := stores.Task.Create(&model.Task{
Name: "2",
MaxPoints: 31,
PublicDockerImage: null.StringFrom("ff"),
PrivateDockerImage: null.StringFrom("ff"),
}, sheet2.ID)

_ = task1
_ = task2
g.Assert(err).Equal(nil)

uid1 := int64(42)
uid2 := int64(43)
Expand Down
4 changes: 4 additions & 0 deletions api/app/group.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ func (rs *GroupResource) IndexHandler(w http.ResponseWriter, r *http.Request) {

course := r.Context().Value(common.CtxKeyCourse).(*model.Course)
groups, err = rs.Stores.Group.GroupsOfCourse(course.ID)
if err != nil {
render.Render(w, r, ErrInternalServerErrorWithDetails(err))
return
}

// render JSON reponse
if err = render.RenderList(w, r, rs.newGroupListResponse(groups)); err != nil {
Expand Down
1 change: 1 addition & 0 deletions api/app/group_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ func TestGroup(t *testing.T) {

entryReturn := &GroupResponse{}
err = json.NewDecoder(w.Body).Decode(&entryReturn)
g.Assert(err).Equal(nil)
g.Assert(entryReturn.Tutor.ID).Equal(tutorID)
g.Assert(entryReturn.CourseID).Equal(int64(1))
g.Assert(entryReturn.Description).Equal("blah blahe")
Expand Down
9 changes: 5 additions & 4 deletions api/app/material_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,7 @@ func TestMaterial(t *testing.T) {

// tutors
w, err = tape.UploadWithClaims("/api/v1/courses/1/materials/1/file", filename, "application/zip", 2, false)
g.Assert(err).Equal(nil)
g.Assert(w.Code).Equal(http.StatusForbidden)

// admin
Expand Down Expand Up @@ -339,13 +340,13 @@ func TestMaterial(t *testing.T) {

// a file should be now served
w = tape.GetWithClaims("/api/v1/courses/1/materials/1/file", 1, true)
g.Assert(w.HeaderMap["Content-Type"][0]).Equal("application/zip")
g.Assert(w.Header().Get("Content-Type")).Equal("application/zip")
g.Assert(w.Code).Equal(http.StatusOK)

course, err := stores.Material.IdentifyCourseOfMaterial(1)
g.Assert(err).Equal(nil)

_, params, err := mime.ParseMediaType(w.HeaderMap["Content-Disposition"][0])
_, params, err := mime.ParseMediaType(w.Header().Get("Content-Disposition"))
g.Assert(err).Equal(nil)
g.Assert(params["filename"]).Equal(fmt.Sprintf("%s-empty.zip", course.Name))
})
Expand All @@ -364,13 +365,13 @@ func TestMaterial(t *testing.T) {

// a file should be now served
w = tape.GetWithClaims("/api/v1/courses/1/materials/1/file", 1, true)
g.Assert(w.HeaderMap["Content-Type"][0]).Equal("application/pdf")
g.Assert(w.Header().Get("Content-Type")).Equal("application/pdf")
g.Assert(w.Code).Equal(http.StatusOK)

course, err := stores.Material.IdentifyCourseOfMaterial(1)
g.Assert(err).Equal(nil)

_, params, err := mime.ParseMediaType(w.HeaderMap["Content-Disposition"][0])
_, params, err := mime.ParseMediaType(w.Header().Get("Content-Disposition"))
g.Assert(err).Equal(nil)
g.Assert(params["filename"]).Equal(fmt.Sprintf("%s-empty.pdf", course.Name))
})
Expand Down
4 changes: 4 additions & 0 deletions api/app/sheet.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ func (rs *SheetResource) IndexHandler(w http.ResponseWriter, r *http.Request) {

course := r.Context().Value(common.CtxKeyCourse).(*model.Course)
sheets, err = rs.Stores.Sheet.SheetsOfCourse(course.ID)
if err != nil {
render.Render(w, r, ErrInternalServerErrorWithDetails(err))
return
}

givenRole := r.Context().Value(common.CtxKeyCourseRole).(authorize.CourseRole)

Expand Down
1 change: 1 addition & 0 deletions api/app/sheet_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ func TestSheet(t *testing.T) {

// tutors
w, err = tape.UploadWithClaims("/api/v1/courses/1/sheets/1/file", filename, "application/zip", 2, false)
g.Assert(err).Equal(nil)
g.Assert(w.Code).Equal(http.StatusForbidden)

// admin
Expand Down
4 changes: 4 additions & 0 deletions api/app/task.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ func (rs *TaskResource) IndexHandler(w http.ResponseWriter, r *http.Request) {
// we use middle to detect whether there is a sheet given
sheet := r.Context().Value(common.CtxKeySheet).(*model.Sheet)
tasks, err = rs.Stores.Task.TasksOfSheet(sheet.ID)
if err != nil {
render.Render(w, r, ErrInternalServerErrorWithDetails(err))
return
}

// render JSON reponse
if err = render.RenderList(w, r, newTaskListResponse(tasks)); err != nil {
Expand Down
1 change: 1 addition & 0 deletions api/app/task_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ func TestTask(t *testing.T) {

taskReturn := &TaskResponse{}
err = json.NewDecoder(w.Body).Decode(&taskReturn)
g.Assert(err).Equal(nil)
g.Assert(taskReturn.Name).Equal("new Task")
g.Assert(taskReturn.MaxPoints).Equal(88)
g.Assert(taskReturn.PrivateDockerImage.Valid).Equal(true)
Expand Down
4 changes: 4 additions & 0 deletions api/app/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ func (rs *UserResource) IndexHandler(w http.ResponseWriter, r *http.Request) {

// fetch collection of users from database
users, err := rs.Stores.User.GetAll()
if err != nil {
render.Render(w, r, ErrInternalServerErrorWithDetails(err))
return
}

// render JSON reponse
if err = render.RenderList(w, r, newUserListResponse(users)); err != nil {
Expand Down
2 changes: 0 additions & 2 deletions api/cronjob/submission_zipper.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,6 @@ Please log in to grade these solutions.
fmt.Println(" --> already done", sheet.ID)
}

} else {
// fmt.Println("ok", sheet.ID)
}

}
Expand Down
9 changes: 7 additions & 2 deletions api/helper/file_carrier.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,9 +212,14 @@ func FileExists(path string) bool {
}

// FileTouch creates an empty file
func FileTouch(path string) error {
func FileTouch(path string) (err error) {
emptyFile, err := os.Create(path)
defer emptyFile.Close()

defer func() {
if lerr := emptyFile.Close(); lerr != nil {
err = lerr
}
}()
return err
}

Expand Down
2 changes: 1 addition & 1 deletion api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ func (srv *Server) Start() {
log.Info("starting cronjob for zipping submissions...")
srv.Cron.Start()

quit := make(chan os.Signal)
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
sig := <-quit
log.Info("Shutting down server... Reason:", sig)
Expand Down
2 changes: 1 addition & 1 deletion api/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func (srv *Worker) Start() {

go consumer.HandleLoop(deliveries)

quit := make(chan os.Signal)
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
sig := <-quit
log.Println("Shutting down Worker... Reason:", sig)
Expand Down
10 changes: 10 additions & 0 deletions api/worker/submission_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,11 @@ func (h *RealSubmissionHandler) Handle(body []byte) error {

// 2. fetch submission file from server
r, err := http.NewRequest("GET", msg.SubmissionFileURL, nil)
if err != nil {
DefaultLogger.Printf("error: %v\n", err)
return err
}

r.Header.Add("Authorization", "Bearer "+msg.AccessToken)
if err := downloadFile(r, submissionPath); err != nil {
DefaultLogger.Printf("error: %v\n", err)
Expand All @@ -210,7 +215,12 @@ func (h *RealSubmissionHandler) Handle(body []byte) error {

// 3. fetch framework file from server
r, err = http.NewRequest("GET", msg.FrameworkFileURL, nil)
if err != nil {
DefaultLogger.Printf("error: %v\n", err)
return err
}
r.Header.Add("Authorization", "Bearer "+msg.AccessToken)

if err := downloadFile(r, frameworkPath); err != nil {
DefaultLogger.Printf("error: %v\n", err)
return err
Expand Down
8 changes: 5 additions & 3 deletions auth/authenticate/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,6 @@ func RequiredValidAccessClaims(next http.Handler) http.Handler {
// serve next
ctx := context.WithValue(r.Context(), common.CtxKeyAccessClaims, accessClaims)
next.ServeHTTP(w, r.WithContext(ctx))
return

})
}

Expand Down Expand Up @@ -146,6 +144,10 @@ func NewLoginLimiter(prefix string, limit string, redisURL string) (*LoginLimite
MaxRetry: 3,
})

if err != nil {
return nil, err
}

// store := memory.NewStore()

return &LoginLimiter{Store: &store, Rate: &rate, Prefix: prefix}, nil
Expand Down Expand Up @@ -182,7 +184,7 @@ func RateLimitMiddleware(prefix string, limit string, redisURL string) func(h ht

context, err := ll.Get(r, keyFunc)
if err != nil {
panic(err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}

Expand Down
2 changes: 1 addition & 1 deletion cmd/console.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ var UtilsCompletionCmd = &cobra.Command{
case "zsh":
RootCmd.GenZshCompletion(os.Stdout)
default:
log.Fatalln("Unknown shell %s, only bash and zsh are available\n", args[0])
log.Fatalf("Unknown shell %s, only bash and zsh are available\n", args[0])
}
},
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/console/course_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,12 @@ var UserEnrollInCourse = &cobra.Command{

user, err := stores.User.Get(userID)
if err != nil {
log.Fatal("user with id %v not found\n", userID)
log.Fatalf("user with id %v not found\n", userID)
}

course, err := stores.Course.Get(courseID)
if err != nil {
log.Fatal("user with id %v not found\n", userID)
log.Fatalf("user with id %v not found\n", userID)
}

if err := stores.Course.Enroll(course.ID, user.ID, role); err != nil {
Expand Down
7 changes: 5 additions & 2 deletions cmd/console/database_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ var DatabaseRestoreCmd = &cobra.Command{
err = shell2.Wait()
// io.Copy(os.Stdout, &b2)
if err != nil {
log.Fatal("load db from was not successfull\n %s", err)
log.Fatalf("load db from was not successfull\n %s", err)
}
},
}
Expand Down Expand Up @@ -211,6 +211,9 @@ var DatabaseBackupCmd = &cobra.Command{
shell1.Wait()
w.Close()
err := shell2.Wait()
if err != nil {
panic(err)
}

destination, err := os.Create(file)
if err != nil {
Expand All @@ -219,7 +222,7 @@ var DatabaseBackupCmd = &cobra.Command{
defer destination.Close()
_, err = io.Copy(destination, &b2)
if err != nil {
log.Fatal("storing snapshot was not successfull\n %s", err)
log.Fatalf("storing snapshot was not successfull\n %s", err)
}

},
Expand Down
1 change: 1 addition & 0 deletions cmd/console/group_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,7 @@ var GroupParseBidsSolution = &cobra.Command{

// we perform the update as a transaction
tx, err := db.Begin()
failWhenSmallestWhiff(err)
// delete assignments so far
_, err = tx.Exec(`
DELETE FROM
Expand Down
Loading

0 comments on commit d5e5031

Please sign in to comment.