Skip to content

Commit 4737a8d

Browse files
committed
Various fixes:
nil point dereference panic on wrong content-type Signed-off-by: David Kröll <[email protected]>
1 parent 7aa2b60 commit 4737a8d

File tree

5 files changed

+13
-4
lines changed

5 files changed

+13
-4
lines changed

main.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,5 +37,5 @@ func main() {
3737
}
3838

3939
router := routes.InitRouter()
40-
log.Fatal(http.ListenAndServe(":"+os.Getenv("PORT"), router))
40+
log.Fatal(http.ListenAndServe(":"+os.Getenv("PORT"), &router))
4141
}

models/database.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ func InitDatabase(config DBConfig) *Database {
3939
database.SetMaxIdleConns(4)
4040

4141
// check if database is available
42-
if err := db.Ping(); err != nil {
42+
if err := database.Ping(); err != nil {
4343
log.Fatal(err)
4444
}
4545

routes/http_bodies.go

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package routes
2+
3+
type ErrorResponse struct {
4+
Message string `json:"message"`
5+
}

routes/middlewares.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package routes
22

33
import (
4+
"encoding/json"
45
"log"
56
"net/http"
67
)
@@ -24,7 +25,10 @@ func HeaderBinding(next http.Handler) http.Handler {
2425

2526
if r.Method == "POST" {
2627
if r.Header.Get("Content-Type") != "application/json" {
27-
log.Fatal("Wrong Content-Type in POST request. application/json expected")
28+
_ = json.NewEncoder(w).Encode(ErrorResponse{
29+
"Wrong Content-Type in POST request. application/json expected",
30+
})
31+
return
2832
}
2933
}
3034

routes/router.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import (
44
"github.com/gorilla/mux"
55
)
66

7-
func InitRouter() (router *mux.Router) {
7+
func InitRouter() (router mux.Router) {
88
router.Use(RequestLogger, HeaderBinding)
99
router.HandleFunc("/users/auth/new", registerUser).Methods("POST")
1010
router.HandleFunc("/users/auth", loginUser).Methods("POST")

0 commit comments

Comments
 (0)