From c9add39768a416ebd5df7a7ee220ab193a4a6d0c Mon Sep 17 00:00:00 2001 From: Scott Raine Date: Tue, 13 Mar 2018 11:55:45 -0400 Subject: [PATCH] Use http.Status* and http.Method* where appropriate (#417) Signed-off-by: Scott Raine --- .../dendrite/clientapi/auth/auth.go | 4 +- .../dendrite/clientapi/httputil/httputil.go | 2 +- .../dendrite/clientapi/jsonerror/jsonerror.go | 3 +- .../clientapi/routing/account_data.go | 8 +- .../dendrite/clientapi/routing/createroom.go | 6 +- .../dendrite/clientapi/routing/device.go | 16 +-- .../dendrite/clientapi/routing/directory.go | 20 ++-- .../dendrite/clientapi/routing/filter.go | 16 +-- .../dendrite/clientapi/routing/joinroom.go | 18 +-- .../dendrite/clientapi/routing/login.go | 20 ++-- .../dendrite/clientapi/routing/logout.go | 8 +- .../dendrite/clientapi/routing/membership.go | 14 +-- .../dendrite/clientapi/routing/memberships.go | 4 +- .../dendrite/clientapi/routing/profile.go | 22 ++-- .../dendrite/clientapi/routing/register.go | 70 ++++++------ .../dendrite/clientapi/routing/routing.go | 106 +++++++++--------- .../dendrite/clientapi/routing/sendevent.go | 6 +- .../dendrite/clientapi/routing/threepid.go | 18 +-- .../dendrite/clientapi/routing/voip.go | 9 +- .../dendrite/clientapi/threepid/invites.go | 6 +- .../dendrite/clientapi/threepid/threepid.go | 6 +- .../matrix-org/dendrite/common/httpapi.go | 2 +- .../dendrite/federationapi/routing/events.go | 7 +- .../dendrite/federationapi/routing/invite.go | 12 +- .../dendrite/federationapi/routing/join.go | 22 ++-- .../dendrite/federationapi/routing/keys.go | 3 +- .../dendrite/federationapi/routing/profile.go | 6 +- .../dendrite/federationapi/routing/query.go | 12 +- .../dendrite/federationapi/routing/routing.go | 24 ++-- .../dendrite/federationapi/routing/send.go | 4 +- .../federationapi/routing/threepid.go | 14 +-- .../dendrite/federationapi/routing/version.go | 4 +- .../dendrite/mediaapi/routing/download.go | 20 ++-- .../dendrite/mediaapi/routing/routing.go | 6 +- .../dendrite/mediaapi/routing/upload.go | 24 ++-- .../publicroomsapi/directory/directory.go | 4 +- .../publicroomsapi/directory/public_rooms.go | 8 +- .../publicroomsapi/routing/routing.go | 6 +- .../dendrite/roomserver/alias/alias.go | 6 +- .../dendrite/roomserver/api/query.go | 7 +- .../dendrite/roomserver/input/input.go | 4 +- .../dendrite/roomserver/query/query.go | 14 +-- .../dendrite/syncapi/routing/routing.go | 8 +- .../dendrite/syncapi/routing/state.go | 6 +- .../dendrite/syncapi/sync/requestpool.go | 8 +- 45 files changed, 308 insertions(+), 305 deletions(-) diff --git a/src/github.com/matrix-org/dendrite/clientapi/auth/auth.go b/src/github.com/matrix-org/dendrite/clientapi/auth/auth.go index 56ee31ecb..f44b6eea7 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/auth/auth.go +++ b/src/github.com/matrix-org/dendrite/clientapi/auth/auth.go @@ -50,7 +50,7 @@ func VerifyAccessToken(req *http.Request, deviceDB DeviceDatabase) (device *auth token, err := extractAccessToken(req) if err != nil { resErr = &util.JSONResponse{ - Code: 401, + Code: http.StatusUnauthorized, JSON: jsonerror.MissingToken(err.Error()), } return @@ -59,7 +59,7 @@ func VerifyAccessToken(req *http.Request, deviceDB DeviceDatabase) (device *auth if err != nil { if err == sql.ErrNoRows { resErr = &util.JSONResponse{ - Code: 401, + Code: http.StatusUnauthorized, JSON: jsonerror.UnknownToken("Unknown token"), } } else { diff --git a/src/github.com/matrix-org/dendrite/clientapi/httputil/httputil.go b/src/github.com/matrix-org/dendrite/clientapi/httputil/httputil.go index 8135b9ddb..bc7e67e0f 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/httputil/httputil.go +++ b/src/github.com/matrix-org/dendrite/clientapi/httputil/httputil.go @@ -31,7 +31,7 @@ func UnmarshalJSONRequest(req *http.Request, iface interface{}) *util.JSONRespon // debugging because an error will be produced for both invalid/malformed JSON AND // valid JSON with incorrect types for values. return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("The request body could not be decoded into valid JSON. " + err.Error()), } } diff --git a/src/github.com/matrix-org/dendrite/clientapi/jsonerror/jsonerror.go b/src/github.com/matrix-org/dendrite/clientapi/jsonerror/jsonerror.go index 571ed49b3..e0313def3 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/jsonerror/jsonerror.go +++ b/src/github.com/matrix-org/dendrite/clientapi/jsonerror/jsonerror.go @@ -16,6 +16,7 @@ package jsonerror import ( "fmt" + "net/http" "github.com/matrix-org/util" ) @@ -35,7 +36,7 @@ func (e *MatrixError) Error() string { // format. func InternalServerError() util.JSONResponse { return util.JSONResponse{ - Code: 500, + Code: http.StatusInternalServerError, JSON: Unknown("Internal Server Error"), } } diff --git a/src/github.com/matrix-org/dendrite/clientapi/routing/account_data.go b/src/github.com/matrix-org/dendrite/clientapi/routing/account_data.go index bd387eb96..30e00f723 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/routing/account_data.go +++ b/src/github.com/matrix-org/dendrite/clientapi/routing/account_data.go @@ -33,16 +33,16 @@ func SaveAccountData( req *http.Request, accountDB *accounts.Database, device *authtypes.Device, userID string, roomID string, dataType string, syncProducer *producers.SyncAPIProducer, ) util.JSONResponse { - if req.Method != "PUT" { + if req.Method != http.MethodPut { return util.JSONResponse{ - Code: 405, + Code: http.StatusMethodNotAllowed, JSON: jsonerror.NotFound("Bad method"), } } if userID != device.UserID { return util.JSONResponse{ - Code: 403, + Code: http.StatusForbidden, JSON: jsonerror.Forbidden("userID does not match the current user"), } } @@ -70,7 +70,7 @@ func SaveAccountData( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct{}{}, } } diff --git a/src/github.com/matrix-org/dendrite/clientapi/routing/createroom.go b/src/github.com/matrix-org/dendrite/clientapi/routing/createroom.go index f7956d29a..05751f23a 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/routing/createroom.go +++ b/src/github.com/matrix-org/dendrite/clientapi/routing/createroom.go @@ -70,7 +70,7 @@ func (r createRoomRequest) Validate() *util.JSONResponse { // Synapse doesn't check for ':' but we will else it will break parsers badly which split things into 2 segments. if strings.ContainsAny(r.RoomAliasName, whitespace+":") { return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("room_alias_name cannot contain whitespace"), } } @@ -82,7 +82,7 @@ func (r createRoomRequest) Validate() *util.JSONResponse { // https://github.com/matrix-org/synapse/blob/v0.19.2/synapse/types.py#L92 if _, _, err := gomatrixserverlib.SplitID('@', userID); err != nil { return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("user id must be in the form @localpart:domain"), } } @@ -92,7 +92,7 @@ func (r createRoomRequest) Validate() *util.JSONResponse { break default: return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("preset must be any of 'private_chat', 'trusted_private_chat', 'public_chat'"), } } diff --git a/src/github.com/matrix-org/dendrite/clientapi/routing/device.go b/src/github.com/matrix-org/dendrite/clientapi/routing/device.go index 75df2e6e4..d519c8a6a 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/routing/device.go +++ b/src/github.com/matrix-org/dendrite/clientapi/routing/device.go @@ -54,7 +54,7 @@ func GetDeviceByID( dev, err := deviceDB.GetDeviceByID(ctx, localpart, deviceID) if err == sql.ErrNoRows { return util.JSONResponse{ - Code: 404, + Code: http.StatusNotFound, JSON: jsonerror.NotFound("Unknown device"), } } else if err != nil { @@ -62,7 +62,7 @@ func GetDeviceByID( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: deviceJSON{ DeviceID: dev.ID, UserID: dev.UserID, @@ -96,7 +96,7 @@ func GetDevicesByLocalpart( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: res, } } @@ -106,9 +106,9 @@ func UpdateDeviceByID( req *http.Request, deviceDB *devices.Database, device *authtypes.Device, deviceID string, ) util.JSONResponse { - if req.Method != "PUT" { + if req.Method != http.MethodPut { return util.JSONResponse{ - Code: 405, + Code: http.StatusMethodNotAllowed, JSON: jsonerror.NotFound("Bad Method"), } } @@ -122,7 +122,7 @@ func UpdateDeviceByID( dev, err := deviceDB.GetDeviceByID(ctx, localpart, deviceID) if err == sql.ErrNoRows { return util.JSONResponse{ - Code: 404, + Code: http.StatusNotFound, JSON: jsonerror.NotFound("Unknown device"), } } else if err != nil { @@ -131,7 +131,7 @@ func UpdateDeviceByID( if dev.UserID != device.UserID { return util.JSONResponse{ - Code: 403, + Code: http.StatusForbidden, JSON: jsonerror.Forbidden("device not owned by current user"), } } @@ -149,7 +149,7 @@ func UpdateDeviceByID( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct{}{}, } } diff --git a/src/github.com/matrix-org/dendrite/clientapi/routing/directory.go b/src/github.com/matrix-org/dendrite/clientapi/routing/directory.go index 13ab8e2b8..d497d1071 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/routing/directory.go +++ b/src/github.com/matrix-org/dendrite/clientapi/routing/directory.go @@ -38,7 +38,7 @@ func DirectoryRoom( _, domain, err := gomatrixserverlib.SplitID('#', roomAlias) if err != nil { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("Room alias must be in the form '#localpart:domain'"), } } @@ -61,7 +61,7 @@ func DirectoryRoom( } else { // If the response doesn't contain a non-empty string, return an error return util.JSONResponse{ - Code: 404, + Code: http.StatusNotFound, JSON: jsonerror.NotFound("Room alias " + roomAlias + " not found."), } } @@ -70,9 +70,9 @@ func DirectoryRoom( if err != nil { switch x := err.(type) { case gomatrix.HTTPError: - if x.Code == 404 { + if x.Code == http.StatusNotFound { return util.JSONResponse{ - Code: 404, + Code: http.StatusNotFound, JSON: jsonerror.NotFound("Room alias not found"), } } @@ -84,7 +84,7 @@ func DirectoryRoom( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: resp, } } @@ -101,14 +101,14 @@ func SetLocalAlias( _, domain, err := gomatrixserverlib.SplitID('#', alias) if err != nil { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("Room alias must be in the form '#localpart:domain'"), } } if domain != cfg.Matrix.ServerName { return util.JSONResponse{ - Code: 403, + Code: http.StatusForbidden, JSON: jsonerror.Forbidden("Alias must be on local homeserver"), } } @@ -132,13 +132,13 @@ func SetLocalAlias( if queryRes.AliasExists { return util.JSONResponse{ - Code: 409, + Code: http.StatusConflict, JSON: jsonerror.Unknown("The alias " + alias + " already exists."), } } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct{}{}, } } @@ -161,7 +161,7 @@ func RemoveLocalAlias( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct{}{}, } } diff --git a/src/github.com/matrix-org/dendrite/clientapi/routing/filter.go b/src/github.com/matrix-org/dendrite/clientapi/routing/filter.go index 4b84e293d..109c55da1 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/routing/filter.go +++ b/src/github.com/matrix-org/dendrite/clientapi/routing/filter.go @@ -34,13 +34,13 @@ func GetFilter( ) util.JSONResponse { if req.Method != http.MethodGet { return util.JSONResponse{ - Code: 405, + Code: http.StatusMethodNotAllowed, JSON: jsonerror.NotFound("Bad method"), } } if userID != device.UserID { return util.JSONResponse{ - Code: 403, + Code: http.StatusForbidden, JSON: jsonerror.Forbidden("Cannot get filters for other users"), } } @@ -55,7 +55,7 @@ func GetFilter( // but if there are obscure db errors, this will also be returned, // even though it is not correct. return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.NotFound("No such filter"), } } @@ -66,7 +66,7 @@ func GetFilter( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: filter, } } @@ -81,13 +81,13 @@ func PutFilter( ) util.JSONResponse { if req.Method != http.MethodPost { return util.JSONResponse{ - Code: 405, + Code: http.StatusMethodNotAllowed, JSON: jsonerror.NotFound("Bad method"), } } if userID != device.UserID { return util.JSONResponse{ - Code: 403, + Code: http.StatusForbidden, JSON: jsonerror.Forbidden("Cannot create filters for other users"), } } @@ -106,7 +106,7 @@ func PutFilter( filterArray, err := json.Marshal(filter) if err != nil { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("Filter is malformed"), } } @@ -117,7 +117,7 @@ func PutFilter( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: filterResponse{FilterID: filterID}, } } diff --git a/src/github.com/matrix-org/dendrite/clientapi/routing/joinroom.go b/src/github.com/matrix-org/dendrite/clientapi/routing/joinroom.go index aba49cd65..806c5f08b 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/routing/joinroom.go +++ b/src/github.com/matrix-org/dendrite/clientapi/routing/joinroom.go @@ -75,7 +75,7 @@ func JoinRoomByIDOrAlias( return r.joinRoomByAlias(roomIDOrAlias) } return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("Invalid first character for room ID or alias"), } } @@ -114,7 +114,7 @@ func (r joinRoomReq) joinRoomByID(roomID string) util.JSONResponse { // joinRoomUsingServers passing an empty list since joinRoomUserServers // will check if we are already in the room first. return util.JSONResponse{ - Code: 403, + Code: http.StatusForbidden, JSON: jsonerror.Forbidden("You are not invited to the room"), } } @@ -140,7 +140,7 @@ func (r joinRoomReq) joinRoomByAlias(roomAlias string) util.JSONResponse { _, domain, err := gomatrixserverlib.SplitID('#', roomAlias) if err != nil { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("Room alias must be in the form '#localpart:domain'"), } } @@ -156,7 +156,7 @@ func (r joinRoomReq) joinRoomByAlias(roomAlias string) util.JSONResponse { } // If the response doesn't contain a non-empty string, return an error return util.JSONResponse{ - Code: 404, + Code: http.StatusNotFound, JSON: jsonerror.NotFound("Room alias " + roomAlias + " not found."), } } @@ -171,9 +171,9 @@ func (r joinRoomReq) joinRoomByRemoteAlias( if err != nil { switch x := err.(type) { case gomatrix.HTTPError: - if x.Code == 404 { + if x.Code == http.StatusNotFound { return util.JSONResponse{ - Code: 404, + Code: http.StatusNotFound, JSON: jsonerror.NotFound("Room alias not found"), } } @@ -221,7 +221,7 @@ func (r joinRoomReq) joinRoomUsingServers( return httputil.LogThenError(r.req, err) } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct { RoomID string `json:"room_id"` }{roomID}, @@ -233,7 +233,7 @@ func (r joinRoomReq) joinRoomUsingServers( if len(servers) == 0 { return util.JSONResponse{ - Code: 404, + Code: http.StatusNotFound, JSON: jsonerror.NotFound("No candidate servers found for room"), } } @@ -312,7 +312,7 @@ func (r joinRoomReq) joinRoomUsingServer(roomID string, server gomatrixserverlib } return &util.JSONResponse{ - Code: 200, + Code: http.StatusOK, // TODO: Put the response struct somewhere common. JSON: struct { RoomID string `json:"room_id"` diff --git a/src/github.com/matrix-org/dendrite/clientapi/routing/login.go b/src/github.com/matrix-org/dendrite/clientapi/routing/login.go index f48261ab2..e0a4e6327 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/routing/login.go +++ b/src/github.com/matrix-org/dendrite/clientapi/routing/login.go @@ -62,12 +62,12 @@ func Login( req *http.Request, accountDB *accounts.Database, deviceDB *devices.Database, cfg config.Dendrite, ) util.JSONResponse { - if req.Method == "GET" { // TODO: support other forms of login other than password, depending on config options + if req.Method == http.MethodGet { // TODO: support other forms of login other than password, depending on config options return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: passwordLogin(), } - } else if req.Method == "POST" { + } else if req.Method == http.MethodPost { var r passwordRequest resErr := httputil.UnmarshalJSONRequest(req, &r) if resErr != nil { @@ -75,7 +75,7 @@ func Login( } if r.User == "" { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("'user' must be supplied."), } } @@ -90,14 +90,14 @@ func Login( localpart, domain, err = gomatrixserverlib.SplitID('@', r.User) if err != nil { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.InvalidUsername("Invalid username"), } } if domain != cfg.Matrix.ServerName { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.InvalidUsername("User ID not ours"), } } @@ -108,7 +108,7 @@ func Login( // Technically we could tell them if the user does not exist by checking if err == sql.ErrNoRows // but that would leak the existence of the user. return util.JSONResponse{ - Code: 403, + Code: http.StatusForbidden, JSON: jsonerror.Forbidden("username or password was incorrect, or the account does not exist"), } } @@ -124,13 +124,13 @@ func Login( ) if err != nil { return util.JSONResponse{ - Code: 500, + Code: http.StatusInternalServerError, JSON: jsonerror.Unknown("failed to create device: " + err.Error()), } } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: loginResponse{ UserID: dev.UserID, AccessToken: dev.AccessToken, @@ -140,7 +140,7 @@ func Login( } } return util.JSONResponse{ - Code: 405, + Code: http.StatusMethodNotAllowed, JSON: jsonerror.NotFound("Bad method"), } } diff --git a/src/github.com/matrix-org/dendrite/clientapi/routing/logout.go b/src/github.com/matrix-org/dendrite/clientapi/routing/logout.go index d03e7957f..d20138534 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/routing/logout.go +++ b/src/github.com/matrix-org/dendrite/clientapi/routing/logout.go @@ -29,9 +29,9 @@ import ( func Logout( req *http.Request, deviceDB *devices.Database, device *authtypes.Device, ) util.JSONResponse { - if req.Method != "POST" { + if req.Method != http.MethodPost { return util.JSONResponse{ - Code: 405, + Code: http.StatusMethodNotAllowed, JSON: jsonerror.NotFound("Bad method"), } } @@ -46,7 +46,7 @@ func Logout( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct{}{}, } } @@ -65,7 +65,7 @@ func LogoutAll( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct{}{}, } } diff --git a/src/github.com/matrix-org/dendrite/clientapi/routing/membership.go b/src/github.com/matrix-org/dendrite/clientapi/routing/membership.go index 8e2e87ad3..46de5b78f 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/routing/membership.go +++ b/src/github.com/matrix-org/dendrite/clientapi/routing/membership.go @@ -53,17 +53,17 @@ func SendMembership( ) if err == threepid.ErrMissingParameter { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON(err.Error()), } } else if err == threepid.ErrNotTrusted { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.NotTrusted(body.IDServer), } } else if err == common.ErrRoomNoExists { return util.JSONResponse{ - Code: 404, + Code: http.StatusNotFound, JSON: jsonerror.NotFound(err.Error()), } } else if err != nil { @@ -75,7 +75,7 @@ func SendMembership( // emit a m.room.member one. if inviteStored { return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct{}{}, } } @@ -85,12 +85,12 @@ func SendMembership( ) if err == errMissingUserID { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON(err.Error()), } } else if err == common.ErrRoomNoExists { return util.JSONResponse{ - Code: 404, + Code: http.StatusNotFound, JSON: jsonerror.NotFound(err.Error()), } } else if err != nil { @@ -104,7 +104,7 @@ func SendMembership( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct{}{}, } } diff --git a/src/github.com/matrix-org/dendrite/clientapi/routing/memberships.go b/src/github.com/matrix-org/dendrite/clientapi/routing/memberships.go index fde278a5b..5b8903287 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/routing/memberships.go +++ b/src/github.com/matrix-org/dendrite/clientapi/routing/memberships.go @@ -48,13 +48,13 @@ func GetMemberships( if !queryRes.HasBeenInRoom { return util.JSONResponse{ - Code: 403, + Code: http.StatusForbidden, JSON: jsonerror.Forbidden("You aren't a member of the room and weren't previously a member of the room."), } } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: response{queryRes.JoinEvents}, } } diff --git a/src/github.com/matrix-org/dendrite/clientapi/routing/profile.go b/src/github.com/matrix-org/dendrite/clientapi/routing/profile.go index ddbae50ca..2013a3580 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/routing/profile.go +++ b/src/github.com/matrix-org/dendrite/clientapi/routing/profile.go @@ -35,9 +35,9 @@ import ( func GetProfile( req *http.Request, accountDB *accounts.Database, userID string, ) util.JSONResponse { - if req.Method != "GET" { + if req.Method != http.MethodGet { return util.JSONResponse{ - Code: 405, + Code: http.StatusMethodNotAllowed, JSON: jsonerror.NotFound("Bad method"), } } @@ -55,7 +55,7 @@ func GetProfile( DisplayName: profile.DisplayName, } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: res, } } @@ -77,7 +77,7 @@ func GetAvatarURL( AvatarURL: profile.AvatarURL, } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: res, } } @@ -90,7 +90,7 @@ func SetAvatarURL( ) util.JSONResponse { if userID != device.UserID { return util.JSONResponse{ - Code: 403, + Code: http.StatusForbidden, JSON: jsonerror.Forbidden("userID does not match the current user"), } } @@ -103,7 +103,7 @@ func SetAvatarURL( } if r.AvatarURL == "" { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("'avatar_url' must be supplied."), } } @@ -147,7 +147,7 @@ func SetAvatarURL( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct{}{}, } } @@ -169,7 +169,7 @@ func GetDisplayName( DisplayName: profile.DisplayName, } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: res, } } @@ -182,7 +182,7 @@ func SetDisplayName( ) util.JSONResponse { if userID != device.UserID { return util.JSONResponse{ - Code: 403, + Code: http.StatusForbidden, JSON: jsonerror.Forbidden("userID does not match the current user"), } } @@ -195,7 +195,7 @@ func SetDisplayName( } if r.DisplayName == "" { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("'displayname' must be supplied."), } } @@ -239,7 +239,7 @@ func SetDisplayName( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct{}{}, } } diff --git a/src/github.com/matrix-org/dendrite/clientapi/routing/register.go b/src/github.com/matrix-org/dendrite/clientapi/routing/register.go index 3d6add044..e9b6050ee 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/routing/register.go +++ b/src/github.com/matrix-org/dendrite/clientapi/routing/register.go @@ -137,17 +137,17 @@ func validateUserName(username string) *util.JSONResponse { // https://github.com/matrix-org/synapse/blob/v0.20.0/synapse/rest/client/v2_alpha/register.py#L161 if len(username) > maxUsernameLength { return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON(fmt.Sprintf("'username' >%d characters", maxUsernameLength)), } } else if !validUsernameRegex.MatchString(username) { return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.InvalidUsername("User ID can only contain characters a-z, 0-9, or '_-./'"), } } else if username[0] == '_' { // Regex checks its not a zero length string return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.InvalidUsername("User ID can't start with a '_'"), } } @@ -159,12 +159,12 @@ func validatePassword(password string) *util.JSONResponse { // https://github.com/matrix-org/synapse/blob/v0.20.0/synapse/rest/client/v2_alpha/register.py#L161 if len(password) > maxPasswordLength { return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON(fmt.Sprintf("'password' >%d characters", maxPasswordLength)), } } else if len(password) > 0 && len(password) < minPasswordLength { return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.WeakPassword(fmt.Sprintf("password too weak: min %d chars", minPasswordLength)), } } @@ -179,14 +179,14 @@ func validateRecaptcha( ) *util.JSONResponse { if !cfg.Matrix.RecaptchaEnabled { return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("Captcha registration is disabled"), } } if response == "" { return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("Captcha response is required"), } } @@ -202,7 +202,7 @@ func validateRecaptcha( if err != nil { return &util.JSONResponse{ - Code: 500, + Code: http.StatusInternalServerError, JSON: jsonerror.BadJSON("Error in requesting validation of captcha response"), } } @@ -215,14 +215,14 @@ func validateRecaptcha( body, err := ioutil.ReadAll(resp.Body) if err != nil { return &util.JSONResponse{ - Code: 500, + Code: http.StatusInternalServerError, JSON: jsonerror.BadJSON("Error in contacting captcha server" + err.Error()), } } err = json.Unmarshal(body, &r) if err != nil { return &util.JSONResponse{ - Code: 500, + Code: http.StatusInternalServerError, JSON: jsonerror.BadJSON("Error in unmarshaling captcha server's response: " + err.Error()), } } @@ -230,7 +230,7 @@ func validateRecaptcha( // Check that we received a "success" if !r.Success { return &util.JSONResponse{ - Code: 401, + Code: http.StatusUnauthorized, JSON: jsonerror.BadJSON("Invalid captcha response. Please try again."), } } @@ -311,7 +311,7 @@ func validateApplicationService( } if matchedApplicationService == nil { return "", &util.JSONResponse{ - Code: 401, + Code: http.StatusUnauthorized, JSON: jsonerror.UnknownToken("Supplied access_token does not match any known application service"), } } @@ -320,7 +320,7 @@ func validateApplicationService( if !UsernameIsWithinApplicationServiceNamespace(cfg, username, matchedApplicationService) { // If we didn't find any matches, return M_EXCLUSIVE return "", &util.JSONResponse{ - Code: 401, + Code: http.StatusUnauthorized, JSON: jsonerror.ASExclusive(fmt.Sprintf( "Supplied username %s did not match any namespaces for application service ID: %s", username, matchedApplicationService.ID)), } @@ -329,7 +329,7 @@ func validateApplicationService( // Check this user does not fit multiple application service namespaces if UsernameMatchesMultipleExclusiveNamespaces(cfg, username) { return "", &util.JSONResponse{ - Code: 401, + Code: http.StatusUnauthorized, JSON: jsonerror.ASExclusive(fmt.Sprintf( "Supplied username %s matches multiple exclusive application service namespaces. Only 1 match allowed", username)), } @@ -364,7 +364,7 @@ func Register( // If no auth type is specified by the client, send back the list of available flows if r.Auth.Type == "" { return util.JSONResponse{ - Code: 401, + Code: http.StatusUnauthorized, JSON: newUserInteractiveResponse(sessionID, cfg.Derived.Registration.Flows, cfg.Derived.Registration.Params), } @@ -386,7 +386,7 @@ func Register( len(cfg.Derived.ApplicationServices) != 0 && cfg.Derived.ExclusiveApplicationServicesUsernameRegexp.MatchString(r.Username) { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.ASExclusive("This username is reserved by an application service."), } } @@ -421,7 +421,7 @@ func handleRegistrationFlow( // TODO: email / msisdn auth types. if cfg.Matrix.RegistrationDisabled && r.Auth.Type != authtypes.LoginTypeSharedSecret { - return util.MessageResponse(403, "Registration has been disabled") + return util.MessageResponse(http.StatusForbidden, "Registration has been disabled") } switch r.Auth.Type { @@ -442,7 +442,7 @@ func handleRegistrationFlow( if err != nil { return httputil.LogThenError(req, err) } else if !valid { - return util.MessageResponse(403, "HMAC incorrect") + return util.MessageResponse(http.StatusForbidden, "HMAC incorrect") } // Add SharedSecret to the list of completed registration stages @@ -470,7 +470,7 @@ func handleRegistrationFlow( default: return util.JSONResponse{ - Code: 501, + Code: http.StatusNotImplemented, JSON: jsonerror.Unknown("unknown/unimplemented auth type"), } } @@ -502,7 +502,7 @@ func checkAndCompleteFlow( // There are still more stages to complete. // Return the flows and those that have been completed. return util.JSONResponse{ - Code: 401, + Code: http.StatusUnauthorized, JSON: newUserInteractiveResponse(sessionID, cfg.Derived.Registration.Flows, cfg.Derived.Registration.Params), } @@ -528,13 +528,13 @@ func LegacyRegister( }).Info("Processing registration request") if cfg.Matrix.RegistrationDisabled && r.Type != authtypes.LoginTypeSharedSecret { - return util.MessageResponse(403, "Registration has been disabled") + return util.MessageResponse(http.StatusForbidden, "Registration has been disabled") } switch r.Type { case authtypes.LoginTypeSharedSecret: if cfg.Matrix.RegistrationSharedSecret == "" { - return util.MessageResponse(400, "Shared secret registration is disabled") + return util.MessageResponse(http.StatusBadRequest, "Shared secret registration is disabled") } valid, err := isValidMacLogin(cfg, r.Username, r.Password, r.Admin, r.Mac) @@ -543,7 +543,7 @@ func LegacyRegister( } if !valid { - return util.MessageResponse(403, "HMAC incorrect") + return util.MessageResponse(http.StatusForbidden, "HMAC incorrect") } return completeRegistration(req.Context(), accountDB, deviceDB, r.Username, r.Password, "", nil) @@ -552,7 +552,7 @@ func LegacyRegister( return completeRegistration(req.Context(), accountDB, deviceDB, r.Username, r.Password, "", nil) default: return util.JSONResponse{ - Code: 501, + Code: http.StatusNotImplemented, JSON: jsonerror.Unknown("unknown/unimplemented auth type"), } } @@ -579,7 +579,7 @@ func parseAndValidateLegacyLogin(req *http.Request, r *legacyRegisterRequest) *u // All registration requests must specify what auth they are using to perform this request if r.Type == "" { return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("invalid type"), } } @@ -596,14 +596,14 @@ func completeRegistration( ) util.JSONResponse { if username == "" { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("missing username"), } } // Blank passwords are only allowed by registered application services if password == "" && appserviceID == "" { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("missing password"), } } @@ -611,12 +611,12 @@ func completeRegistration( acc, err := accountDB.CreateAccount(ctx, username, password, appserviceID) if err != nil { return util.JSONResponse{ - Code: 500, + Code: http.StatusInternalServerError, JSON: jsonerror.Unknown("failed to create account: " + err.Error()), } } else if acc == nil { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.UserInUse("Desired user ID is already taken."), } } @@ -624,7 +624,7 @@ func completeRegistration( token, err := auth.GenerateAccessToken() if err != nil { return util.JSONResponse{ - Code: 500, + Code: http.StatusInternalServerError, JSON: jsonerror.Unknown("Failed to generate access token"), } } @@ -633,13 +633,13 @@ func completeRegistration( dev, err := deviceDB.CreateDevice(ctx, username, nil, token, displayName) if err != nil { return util.JSONResponse{ - Code: 500, + Code: http.StatusInternalServerError, JSON: jsonerror.Unknown("failed to create device: " + err.Error()), } } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: registerResponse{ UserID: dev.UserID, AccessToken: dev.AccessToken, @@ -765,19 +765,19 @@ func RegisterAvailable( availability, availabilityErr := accountDB.CheckAccountAvailability(req.Context(), username) if availabilityErr != nil { return util.JSONResponse{ - Code: 500, + Code: http.StatusInternalServerError, JSON: jsonerror.Unknown("failed to check availability: " + availabilityErr.Error()), } } if !availability { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.InvalidUsername("A different user ID has already been registered for this session"), } } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: availableResponse{ Available: true, }, diff --git a/src/github.com/matrix-org/dendrite/clientapi/routing/routing.go b/src/github.com/matrix-org/dendrite/clientapi/routing/routing.go index a7999bf49..1a0252511 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/routing/routing.go +++ b/src/github.com/matrix-org/dendrite/clientapi/routing/routing.go @@ -53,7 +53,7 @@ func Setup( apiMux.Handle("/_matrix/client/versions", common.MakeExternalAPI("versions", func(req *http.Request) util.JSONResponse { return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct { Versions []string `json:"versions"` }{[]string{ @@ -63,7 +63,7 @@ func Setup( }}, } }), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) r0mux := apiMux.PathPrefix(pathPrefixR0).Subrouter() v1mux := apiMux.PathPrefix(pathPrefixV1).Subrouter() @@ -73,7 +73,7 @@ func Setup( common.MakeAuthAPI("createRoom", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { return CreateRoom(req, device, cfg, producer, accountDB, aliasAPI) }), - ).Methods("POST", "OPTIONS") + ).Methods(http.MethodPost, http.MethodOptions) r0mux.Handle("/join/{roomIDOrAlias}", common.MakeAuthAPI("join", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) @@ -81,26 +81,26 @@ func Setup( req, device, vars["roomIDOrAlias"], cfg, federation, producer, queryAPI, aliasAPI, keyRing, accountDB, ) }), - ).Methods("POST", "OPTIONS") + ).Methods(http.MethodPost, http.MethodOptions) r0mux.Handle("/rooms/{roomID}/{membership:(?:join|kick|ban|unban|leave|invite)}", common.MakeAuthAPI("membership", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) return SendMembership(req, accountDB, device, vars["roomID"], vars["membership"], cfg, queryAPI, producer) }), - ).Methods("POST", "OPTIONS") + ).Methods(http.MethodPost, http.MethodOptions) r0mux.Handle("/rooms/{roomID}/send/{eventType}", common.MakeAuthAPI("send_message", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) return SendEvent(req, device, vars["roomID"], vars["eventType"], nil, nil, cfg, queryAPI, producer) }), - ).Methods("POST", "OPTIONS") + ).Methods(http.MethodPost, http.MethodOptions) r0mux.Handle("/rooms/{roomID}/send/{eventType}/{txnID}", common.MakeAuthAPI("send_message", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) txnID := vars["txnID"] return SendEvent(req, device, vars["roomID"], vars["eventType"], &txnID, nil, cfg, queryAPI, producer) }), - ).Methods("PUT", "OPTIONS") + ).Methods(http.MethodPut, http.MethodOptions) r0mux.Handle("/rooms/{roomID}/state/{eventType:[^/]+/?}", common.MakeAuthAPI("send_message", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) @@ -112,59 +112,59 @@ func Setup( } return SendEvent(req, device, vars["roomID"], eventType, nil, &emptyString, cfg, queryAPI, producer) }), - ).Methods("PUT", "OPTIONS") + ).Methods(http.MethodPut, http.MethodOptions) r0mux.Handle("/rooms/{roomID}/state/{eventType}/{stateKey}", common.MakeAuthAPI("send_message", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) stateKey := vars["stateKey"] return SendEvent(req, device, vars["roomID"], vars["eventType"], nil, &stateKey, cfg, queryAPI, producer) }), - ).Methods("PUT", "OPTIONS") + ).Methods(http.MethodPut, http.MethodOptions) r0mux.Handle("/register", common.MakeExternalAPI("register", func(req *http.Request) util.JSONResponse { return Register(req, accountDB, deviceDB, &cfg) - })).Methods("POST", "OPTIONS") + })).Methods(http.MethodPost, http.MethodOptions) v1mux.Handle("/register", common.MakeExternalAPI("register", func(req *http.Request) util.JSONResponse { return LegacyRegister(req, accountDB, deviceDB, &cfg) - })).Methods("POST", "OPTIONS") + })).Methods(http.MethodPost, http.MethodOptions) r0mux.Handle("/register/available", common.MakeExternalAPI("registerAvailable", func(req *http.Request) util.JSONResponse { return RegisterAvailable(req, accountDB) - })).Methods("GET", "OPTIONS") + })).Methods(http.MethodGet, http.MethodOptions) r0mux.Handle("/directory/room/{roomAlias}", common.MakeAuthAPI("directory_room", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) return DirectoryRoom(req, vars["roomAlias"], federation, &cfg, aliasAPI) }), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) r0mux.Handle("/directory/room/{roomAlias}", common.MakeAuthAPI("directory_room", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) return SetLocalAlias(req, device, vars["roomAlias"], &cfg, aliasAPI) }), - ).Methods("PUT", "OPTIONS") + ).Methods(http.MethodPut, http.MethodOptions) r0mux.Handle("/directory/room/{roomAlias}", common.MakeAuthAPI("directory_room", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) return RemoveLocalAlias(req, device, vars["roomAlias"], aliasAPI) }), - ).Methods("DELETE", "OPTIONS") + ).Methods(http.MethodDelete, http.MethodOptions) r0mux.Handle("/logout", common.MakeAuthAPI("logout", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { return Logout(req, deviceDB, device) }), - ).Methods("POST", "OPTIONS") + ).Methods(http.MethodPost, http.MethodOptions) r0mux.Handle("/logout/all", common.MakeAuthAPI("logout", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { return LogoutAll(req, deviceDB, device) }), - ).Methods("POST", "OPTIONS") + ).Methods(http.MethodPost, http.MethodOptions) // Stub endpoints required by Riot @@ -172,7 +172,7 @@ func Setup( common.MakeExternalAPI("login", func(req *http.Request) util.JSONResponse { return Login(req, accountDB, deviceDB, cfg) }), - ).Methods("GET", "POST", "OPTIONS") + ).Methods(http.MethodGet, http.MethodPost, http.MethodOptions) r0mux.Handle("/pushrules/", common.MakeExternalAPI("push_rules", func(req *http.Request) util.JSONResponse { @@ -187,25 +187,25 @@ func Setup( } }`) return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: &res, } }), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) r0mux.Handle("/user/{userId}/filter", common.MakeAuthAPI("put_filter", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) return PutFilter(req, device, accountDB, vars["userId"]) }), - ).Methods("POST", "OPTIONS") + ).Methods(http.MethodPost, http.MethodOptions) r0mux.Handle("/user/{userId}/filter/{filterId}", common.MakeAuthAPI("get_filter", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) return GetFilter(req, device, accountDB, vars["userId"], vars["filterId"]) }), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) // Riot user settings @@ -214,21 +214,21 @@ func Setup( vars := mux.Vars(req) return GetProfile(req, accountDB, vars["userID"]) }), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) r0mux.Handle("/profile/{userID}/avatar_url", common.MakeExternalAPI("profile_avatar_url", func(req *http.Request) util.JSONResponse { vars := mux.Vars(req) return GetAvatarURL(req, accountDB, vars["userID"]) }), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) r0mux.Handle("/profile/{userID}/avatar_url", common.MakeAuthAPI("profile_avatar_url", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) return SetAvatarURL(req, accountDB, device, vars["userID"], userUpdateProducer, &cfg, producer, queryAPI) }), - ).Methods("PUT", "OPTIONS") + ).Methods(http.MethodPut, http.MethodOptions) // Browsers use the OPTIONS HTTP method to check if the CORS policy allows // PUT requests, so we need to allow this method @@ -237,14 +237,14 @@ func Setup( vars := mux.Vars(req) return GetDisplayName(req, accountDB, vars["userID"]) }), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) r0mux.Handle("/profile/{userID}/displayname", common.MakeAuthAPI("profile_displayname", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) return SetDisplayName(req, accountDB, device, vars["userID"], userUpdateProducer, &cfg, producer, queryAPI) }), - ).Methods("PUT", "OPTIONS") + ).Methods(http.MethodPut, http.MethodOptions) // Browsers use the OPTIONS HTTP method to check if the CORS policy allows // PUT requests, so we need to allow this method @@ -252,141 +252,141 @@ func Setup( common.MakeAuthAPI("account_3pid", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { return GetAssociated3PIDs(req, accountDB, device) }), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) r0mux.Handle("/account/3pid", common.MakeAuthAPI("account_3pid", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { return CheckAndSave3PIDAssociation(req, accountDB, device, cfg) }), - ).Methods("POST", "OPTIONS") + ).Methods(http.MethodPost, http.MethodOptions) unstableMux.Handle("/account/3pid/delete", common.MakeAuthAPI("account_3pid", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { return Forget3PID(req, accountDB) }), - ).Methods("POST", "OPTIONS") + ).Methods(http.MethodPost, http.MethodOptions) r0mux.Handle("/{path:(?:account/3pid|register)}/email/requestToken", common.MakeExternalAPI("account_3pid_request_token", func(req *http.Request) util.JSONResponse { return RequestEmailToken(req, accountDB, cfg) }), - ).Methods("POST", "OPTIONS") + ).Methods(http.MethodPost, http.MethodOptions) // Riot logs get flooded unless this is handled r0mux.Handle("/presence/{userID}/status", common.MakeExternalAPI("presence", func(req *http.Request) util.JSONResponse { // TODO: Set presence (probably the responsibility of a presence server not clientapi) return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct{}{}, } }), - ).Methods("PUT", "OPTIONS") + ).Methods(http.MethodPut, http.MethodOptions) r0mux.Handle("/voip/turnServer", common.MakeAuthAPI("turn_server", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { return RequestTurnServer(req, device, cfg) }), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) unstableMux.Handle("/thirdparty/protocols", common.MakeExternalAPI("thirdparty_protocols", func(req *http.Request) util.JSONResponse { // TODO: Return the third party protcols return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct{}{}, } }), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) r0mux.Handle("/rooms/{roomID}/initialSync", common.MakeExternalAPI("rooms_initial_sync", func(req *http.Request) util.JSONResponse { // TODO: Allow people to peek into rooms. return util.JSONResponse{ - Code: 403, + Code: http.StatusForbidden, JSON: jsonerror.GuestAccessForbidden("Guest access not implemented"), } }), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) r0mux.Handle("/user/{userID}/account_data/{type}", common.MakeAuthAPI("user_account_data", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) return SaveAccountData(req, accountDB, device, vars["userID"], "", vars["type"], syncProducer) }), - ).Methods("PUT", "OPTIONS") + ).Methods(http.MethodPut, http.MethodOptions) r0mux.Handle("/user/{userID}/rooms/{roomID}/account_data/{type}", common.MakeAuthAPI("user_account_data", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) return SaveAccountData(req, accountDB, device, vars["userID"], vars["roomID"], vars["type"], syncProducer) }), - ).Methods("PUT", "OPTIONS") + ).Methods(http.MethodPut, http.MethodOptions) r0mux.Handle("/rooms/{roomID}/members", common.MakeAuthAPI("rooms_members", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) return GetMemberships(req, device, vars["roomID"], false, cfg, queryAPI) }), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) r0mux.Handle("/rooms/{roomID}/joined_members", common.MakeAuthAPI("rooms_members", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) return GetMemberships(req, device, vars["roomID"], true, cfg, queryAPI) }), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) r0mux.Handle("/rooms/{roomID}/read_markers", common.MakeExternalAPI("rooms_read_markers", func(req *http.Request) util.JSONResponse { // TODO: return the read_markers. - return util.JSONResponse{Code: 200, JSON: struct{}{}} + return util.JSONResponse{Code: http.StatusOK, JSON: struct{}{}} }), - ).Methods("POST", "OPTIONS") + ).Methods(http.MethodPost, http.MethodOptions) r0mux.Handle("/rooms/{roomID}/typing/{userID}", common.MakeExternalAPI("rooms_typing", func(req *http.Request) util.JSONResponse { // TODO: handling typing - return util.JSONResponse{Code: 200, JSON: struct{}{}} + return util.JSONResponse{Code: http.StatusOK, JSON: struct{}{}} }), - ).Methods("PUT", "OPTIONS") + ).Methods(http.MethodPut, http.MethodOptions) r0mux.Handle("/devices", common.MakeAuthAPI("get_devices", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { return GetDevicesByLocalpart(req, deviceDB, device) }), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) r0mux.Handle("/device/{deviceID}", common.MakeAuthAPI("get_device", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) return GetDeviceByID(req, deviceDB, device, vars["deviceID"]) }), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) r0mux.Handle("/devices/{deviceID}", common.MakeAuthAPI("device_data", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) return UpdateDeviceByID(req, deviceDB, device, vars["deviceID"]) }), - ).Methods("PUT", "OPTIONS") + ).Methods(http.MethodPut, http.MethodOptions) // Stub implementations for sytest r0mux.Handle("/events", common.MakeExternalAPI("events", func(req *http.Request) util.JSONResponse { - return util.JSONResponse{Code: 200, JSON: map[string]interface{}{ + return util.JSONResponse{Code: http.StatusOK, JSON: map[string]interface{}{ "chunk": []interface{}{}, "start": "", "end": "", }} }), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) r0mux.Handle("/initialSync", common.MakeExternalAPI("initial_sync", func(req *http.Request) util.JSONResponse { - return util.JSONResponse{Code: 200, JSON: map[string]interface{}{ + return util.JSONResponse{Code: http.StatusOK, JSON: map[string]interface{}{ "end": "", }} }), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) } diff --git a/src/github.com/matrix-org/dendrite/clientapi/routing/sendevent.go b/src/github.com/matrix-org/dendrite/clientapi/routing/sendevent.go index 5b3803bb1..f47aa0c2d 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/routing/sendevent.go +++ b/src/github.com/matrix-org/dendrite/clientapi/routing/sendevent.go @@ -70,7 +70,7 @@ func SendEvent( e, err := common.BuildEvent(req.Context(), &builder, cfg, queryAPI, &queryRes) if err == common.ErrRoomNoExists { return util.JSONResponse{ - Code: 404, + Code: http.StatusNotFound, JSON: jsonerror.NotFound("Room does not exist"), } } else if err != nil { @@ -85,7 +85,7 @@ func SendEvent( provider := gomatrixserverlib.NewAuthEvents(stateEvents) if err = gomatrixserverlib.Allowed(*e, &provider); err != nil { return util.JSONResponse{ - Code: 403, + Code: http.StatusForbidden, JSON: jsonerror.Forbidden(err.Error()), // TODO: Is this error string comprehensible to the client? } } @@ -106,7 +106,7 @@ func SendEvent( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: sendEventResponse{e.EventID()}, } } diff --git a/src/github.com/matrix-org/dendrite/clientapi/routing/threepid.go b/src/github.com/matrix-org/dendrite/clientapi/routing/threepid.go index dd04b1edd..897d13b63 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/routing/threepid.go +++ b/src/github.com/matrix-org/dendrite/clientapi/routing/threepid.go @@ -56,7 +56,7 @@ func RequestEmailToken(req *http.Request, accountDB *accounts.Database, cfg conf if len(localpart) > 0 { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.MatrixError{ ErrCode: "M_THREEPID_IN_USE", Err: accounts.Err3PIDInUse.Error(), @@ -67,7 +67,7 @@ func RequestEmailToken(req *http.Request, accountDB *accounts.Database, cfg conf resp.SID, err = threepid.CreateSession(req.Context(), body, cfg) if err == threepid.ErrNotTrusted { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.NotTrusted(body.IDServer), } } else if err != nil { @@ -75,7 +75,7 @@ func RequestEmailToken(req *http.Request, accountDB *accounts.Database, cfg conf } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: resp, } } @@ -94,7 +94,7 @@ func CheckAndSave3PIDAssociation( verified, address, medium, err := threepid.CheckAssociation(req.Context(), body.Creds, cfg) if err == threepid.ErrNotTrusted { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.NotTrusted(body.Creds.IDServer), } } else if err != nil { @@ -103,7 +103,7 @@ func CheckAndSave3PIDAssociation( if !verified { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.MatrixError{ ErrCode: "M_THREEPID_AUTH_FAILED", Err: "Failed to auth 3pid", @@ -116,7 +116,7 @@ func CheckAndSave3PIDAssociation( err = threepid.PublishAssociation(body.Creds, device.UserID, cfg) if err == threepid.ErrNotTrusted { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.NotTrusted(body.Creds.IDServer), } } else if err != nil { @@ -135,7 +135,7 @@ func CheckAndSave3PIDAssociation( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct{}{}, } } @@ -155,7 +155,7 @@ func GetAssociated3PIDs( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: threePIDsResponse{threepids}, } } @@ -172,7 +172,7 @@ func Forget3PID(req *http.Request, accountDB *accounts.Database) util.JSONRespon } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct{}{}, } } diff --git a/src/github.com/matrix-org/dendrite/clientapi/routing/voip.go b/src/github.com/matrix-org/dendrite/clientapi/routing/voip.go index 1a2a87527..b9121633f 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/routing/voip.go +++ b/src/github.com/matrix-org/dendrite/clientapi/routing/voip.go @@ -15,12 +15,11 @@ package routing import ( - "net/http" - "crypto/hmac" "crypto/sha1" "encoding/base64" "fmt" + "net/http" "time" "github.com/matrix-org/dendrite/clientapi/auth/authtypes" @@ -38,7 +37,7 @@ func RequestTurnServer(req *http.Request, device *authtypes.Device, cfg config.D // TODO Guest Support if len(turnConfig.URIs) == 0 || turnConfig.UserLifetime == "" { return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct{}{}, } } @@ -67,13 +66,13 @@ func RequestTurnServer(req *http.Request, device *authtypes.Device, cfg config.D resp.Password = turnConfig.Password } else { return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct{}{}, } } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: resp, } } diff --git a/src/github.com/matrix-org/dendrite/clientapi/threepid/invites.go b/src/github.com/matrix-org/dendrite/clientapi/threepid/invites.go index 84ba27641..fba8c928d 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/threepid/invites.go +++ b/src/github.com/matrix-org/dendrite/clientapi/threepid/invites.go @@ -178,7 +178,7 @@ func queryIDServer( func queryIDServerLookup(ctx context.Context, body *MembershipRequest) (*idServerLookupResponse, error) { address := url.QueryEscape(body.Address) url := fmt.Sprintf("https://%s/_matrix/identity/api/v1/lookup?medium=%s&address=%s", body.IDServer, body.Medium, address) - req, err := http.NewRequest("GET", url, nil) + req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return nil, err } @@ -238,7 +238,7 @@ func queryIDServerStoreInvite( // server's database. url := fmt.Sprintf("https://%s/_matrix/identity/api/v1/store-invite", body.IDServer) - req, err := http.NewRequest("POST", url, strings.NewReader(data.Encode())) + req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(data.Encode())) if err != nil { return nil, err } @@ -266,7 +266,7 @@ func queryIDServerStoreInvite( // or if the key couldn't be decoded from base64. func queryIDServerPubKey(ctx context.Context, idServerName string, keyID string) ([]byte, error) { url := fmt.Sprintf("https://%s/_matrix/identity/api/v1/pubkey/%s", idServerName, keyID) - req, err := http.NewRequest("GET", url, nil) + req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return nil, err } diff --git a/src/github.com/matrix-org/dendrite/clientapi/threepid/threepid.go b/src/github.com/matrix-org/dendrite/clientapi/threepid/threepid.go index 1ca3a22ae..db1c45d00 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/threepid/threepid.go +++ b/src/github.com/matrix-org/dendrite/clientapi/threepid/threepid.go @@ -67,7 +67,7 @@ func CreateSession( data.Add("email", req.Email) data.Add("send_attempt", strconv.Itoa(req.SendAttempt)) - request, err := http.NewRequest("POST", postURL, strings.NewReader(data.Encode())) + request, err := http.NewRequest(http.MethodPost, postURL, strings.NewReader(data.Encode())) if err != nil { return "", err } @@ -108,7 +108,7 @@ func CheckAssociation( } url := fmt.Sprintf("https://%s/_matrix/identity/api/v1/3pid/getValidated3pid?sid=%s&client_secret=%s", creds.IDServer, creds.SID, creds.Secret) - req, err := http.NewRequest("GET", url, nil) + req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return false, "", "", err } @@ -154,7 +154,7 @@ func PublishAssociation(creds Credentials, userID string, cfg config.Dendrite) e data.Add("client_secret", creds.Secret) data.Add("mxid", userID) - request, err := http.NewRequest("POST", postURL, strings.NewReader(data.Encode())) + request, err := http.NewRequest(http.MethodPost, postURL, strings.NewReader(data.Encode())) if err != nil { return err } diff --git a/src/github.com/matrix-org/dendrite/common/httpapi.go b/src/github.com/matrix-org/dendrite/common/httpapi.go index b2ef89597..4f6b53eed 100644 --- a/src/github.com/matrix-org/dendrite/common/httpapi.go +++ b/src/github.com/matrix-org/dendrite/common/httpapi.go @@ -101,7 +101,7 @@ func WrapHandlerInCORS(h http.Handler) http.HandlerFunc { w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization") - if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" { + if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" { // Its easiest just to always return a 200 OK for everything. Whether // this is technically correct or not is a question, but in the end this // is what a lot of other people do (including synapse) and the clients diff --git a/src/github.com/matrix-org/dendrite/federationapi/routing/events.go b/src/github.com/matrix-org/dendrite/federationapi/routing/events.go index ed1173113..022628913 100644 --- a/src/github.com/matrix-org/dendrite/federationapi/routing/events.go +++ b/src/github.com/matrix-org/dendrite/federationapi/routing/events.go @@ -16,6 +16,7 @@ package routing import ( "context" + "net/http" "time" "github.com/matrix-org/dendrite/common/config" @@ -48,7 +49,7 @@ func GetEvent( } if !authResponse.AllowedToSeeEvent { - return util.MessageResponse(403, "server not allowed to see event") + return util.MessageResponse(http.StatusForbidden, "server not allowed to see event") } var eventsResponse api.QueryEventsByIDResponse @@ -62,8 +63,8 @@ func GetEvent( } if len(eventsResponse.Events) == 0 { - return util.JSONResponse{Code: 404, JSON: nil} + return util.JSONResponse{Code: http.StatusNotFound, JSON: nil} } - return util.JSONResponse{Code: 200, JSON: &eventsResponse.Events[0]} + return util.JSONResponse{Code: http.StatusOK, JSON: &eventsResponse.Events[0]} } diff --git a/src/github.com/matrix-org/dendrite/federationapi/routing/invite.go b/src/github.com/matrix-org/dendrite/federationapi/routing/invite.go index 26da0d8ce..01a1bed23 100644 --- a/src/github.com/matrix-org/dendrite/federationapi/routing/invite.go +++ b/src/github.com/matrix-org/dendrite/federationapi/routing/invite.go @@ -41,7 +41,7 @@ func Invite( var event gomatrixserverlib.Event if err := json.Unmarshal(request.Content(), &event); err != nil { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.NotJSON("The request body could not be decoded into valid JSON. " + err.Error()), } } @@ -49,7 +49,7 @@ func Invite( // Check that the room ID is correct. if event.RoomID() != roomID { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("The room ID in the request path must match the room ID in the invite event JSON"), } } @@ -57,7 +57,7 @@ func Invite( // Check that the event ID is correct. if event.EventID() != eventID { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("The event ID in the request path must match the event ID in the invite event JSON"), } } @@ -65,7 +65,7 @@ func Invite( // Check that the event is from the server sending the request. if event.Origin() != request.Origin() { return util.JSONResponse{ - Code: 403, + Code: http.StatusForbidden, JSON: jsonerror.Forbidden("The invite must be sent by the server it originated on"), } } @@ -82,7 +82,7 @@ func Invite( } if verifyResults[0].Error != nil { return util.JSONResponse{ - Code: 403, + Code: http.StatusForbidden, JSON: jsonerror.Forbidden("The invite must be signed by the server it originated on"), } } @@ -100,7 +100,7 @@ func Invite( // Return the signed event to the originating server, it should then tell // the other servers in the room that we have been invited. return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: gomatrixserverlib.RespInvite{Event: signedEvent}, } } diff --git a/src/github.com/matrix-org/dendrite/federationapi/routing/join.go b/src/github.com/matrix-org/dendrite/federationapi/routing/join.go index 585c74e6b..d3e63df79 100644 --- a/src/github.com/matrix-org/dendrite/federationapi/routing/join.go +++ b/src/github.com/matrix-org/dendrite/federationapi/routing/join.go @@ -41,13 +41,13 @@ func MakeJoin( _, domain, err := gomatrixserverlib.SplitID('@', userID) if err != nil { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("Invalid UserID"), } } if domain != request.Origin() { return util.JSONResponse{ - Code: 403, + Code: http.StatusForbidden, JSON: jsonerror.Forbidden("The join must be sent by the server of the user"), } } @@ -68,7 +68,7 @@ func MakeJoin( event, err := common.BuildEvent(ctx, &builder, cfg, query, &queryRes) if err == common.ErrRoomNoExists { return util.JSONResponse{ - Code: 404, + Code: http.StatusNotFound, JSON: jsonerror.NotFound("Room does not exist"), } } else if err != nil { @@ -83,13 +83,13 @@ func MakeJoin( provider := gomatrixserverlib.NewAuthEvents(stateEvents) if err = gomatrixserverlib.Allowed(*event, &provider); err != nil { return util.JSONResponse{ - Code: 403, + Code: http.StatusForbidden, JSON: jsonerror.Forbidden(err.Error()), } } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: map[string]interface{}{"event": builder}, } } @@ -108,7 +108,7 @@ func SendJoin( var event gomatrixserverlib.Event if err := json.Unmarshal(request.Content(), &event); err != nil { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.NotJSON("The request body could not be decoded into valid JSON. " + err.Error()), } } @@ -116,7 +116,7 @@ func SendJoin( // Check that the room ID is correct. if event.RoomID() != roomID { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("The room ID in the request path must match the room ID in the join event JSON"), } } @@ -124,7 +124,7 @@ func SendJoin( // Check that the event ID is correct. if event.EventID() != eventID { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("The event ID in the request path must match the event ID in the join event JSON"), } } @@ -132,7 +132,7 @@ func SendJoin( // Check that the event is from the server sending the request. if event.Origin() != request.Origin() { return util.JSONResponse{ - Code: 403, + Code: http.StatusForbidden, JSON: jsonerror.Forbidden("The join must be sent by the server it originated on"), } } @@ -149,7 +149,7 @@ func SendJoin( } if verifyResults[0].Error != nil { return util.JSONResponse{ - Code: 403, + Code: http.StatusForbidden, JSON: jsonerror.Forbidden("The join must be signed by the server it originated on"), } } @@ -175,7 +175,7 @@ func SendJoin( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: map[string]interface{}{ "state": stateAndAuthChainRepsonse.StateEvents, "auth_chain": stateAndAuthChainRepsonse.AuthChainEvents, diff --git a/src/github.com/matrix-org/dendrite/federationapi/routing/keys.go b/src/github.com/matrix-org/dendrite/federationapi/routing/keys.go index b96d8c5c9..9c53d177e 100644 --- a/src/github.com/matrix-org/dendrite/federationapi/routing/keys.go +++ b/src/github.com/matrix-org/dendrite/federationapi/routing/keys.go @@ -16,6 +16,7 @@ package routing import ( "encoding/json" + "net/http" "time" "github.com/matrix-org/dendrite/common/config" @@ -31,7 +32,7 @@ func LocalKeys(cfg config.Dendrite) util.JSONResponse { if err != nil { return util.ErrorResponse(err) } - return util.JSONResponse{Code: 200, JSON: keys} + return util.JSONResponse{Code: http.StatusOK, JSON: keys} } func localKeys(cfg config.Dendrite, validUntil time.Time) (*gomatrixserverlib.ServerKeys, error) { diff --git a/src/github.com/matrix-org/dendrite/federationapi/routing/profile.go b/src/github.com/matrix-org/dendrite/federationapi/routing/profile.go index 715ec4d48..a9cbfca4a 100644 --- a/src/github.com/matrix-org/dendrite/federationapi/routing/profile.go +++ b/src/github.com/matrix-org/dendrite/federationapi/routing/profile.go @@ -37,7 +37,7 @@ func GetProfile( // httpReq.FormValue will return an empty string if value is not found if userID == "" { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.MissingArgument("The request body did not contain required argument 'user_id'."), } } @@ -57,7 +57,7 @@ func GetProfile( } var res interface{} - code := 200 + code := http.StatusOK if field != "" { switch field { @@ -70,7 +70,7 @@ func GetProfile( AvatarURL: profile.AvatarURL, } default: - code = 400 + code = http.StatusBadRequest res = jsonerror.InvalidArgumentValue("The request body did not contain an allowed value of argument 'field'. Allowed values are either: 'avatar_url', 'displayname'.") } } else { diff --git a/src/github.com/matrix-org/dendrite/federationapi/routing/query.go b/src/github.com/matrix-org/dendrite/federationapi/routing/query.go index ef4b8961a..1a604a974 100644 --- a/src/github.com/matrix-org/dendrite/federationapi/routing/query.go +++ b/src/github.com/matrix-org/dendrite/federationapi/routing/query.go @@ -37,14 +37,14 @@ func RoomAliasToID( roomAlias := httpReq.FormValue("alias") if roomAlias == "" { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("Must supply room alias parameter."), } } _, domain, err := gomatrixserverlib.SplitID('#', roomAlias) if err != nil { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("Room alias must be in the form '#localpart:domain'"), } } @@ -67,7 +67,7 @@ func RoomAliasToID( } else { // If the response doesn't contain a non-empty string, return an error return util.JSONResponse{ - Code: 404, + Code: http.StatusNotFound, JSON: jsonerror.NotFound(fmt.Sprintf("Room alias %s not found", roomAlias)), } } @@ -76,9 +76,9 @@ func RoomAliasToID( if err != nil { switch x := err.(type) { case gomatrix.HTTPError: - if x.Code == 404 { + if x.Code == http.StatusNotFound { return util.JSONResponse{ - Code: 404, + Code: http.StatusNotFound, JSON: jsonerror.NotFound("Room alias not found"), } } @@ -90,7 +90,7 @@ func RoomAliasToID( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: resp, } } diff --git a/src/github.com/matrix-org/dendrite/federationapi/routing/routing.go b/src/github.com/matrix-org/dendrite/federationapi/routing/routing.go index a1e2dc2ea..f43866ea1 100644 --- a/src/github.com/matrix-org/dendrite/federationapi/routing/routing.go +++ b/src/github.com/matrix-org/dendrite/federationapi/routing/routing.go @@ -55,8 +55,8 @@ func Setup( // return that key. // Even if we had more than one server key, we would probably still ignore the // {keyID} argument and always return a response containing all of the keys. - v2keysmux.Handle("/server/{keyID}", localKeys).Methods("GET") - v2keysmux.Handle("/server/", localKeys).Methods("GET") + v2keysmux.Handle("/server/{keyID}", localKeys).Methods(http.MethodGet) + v2keysmux.Handle("/server/", localKeys).Methods(http.MethodGet) v1fedmux.Handle("/send/{txnID}/", common.MakeFedAPI( "federation_send", cfg.Matrix.ServerName, keys, @@ -67,7 +67,7 @@ func Setup( cfg, query, producer, keys, federation, ) }, - )).Methods("PUT", "OPTIONS") + )).Methods(http.MethodPut, http.MethodOptions) v1fedmux.Handle("/invite/{roomID}/{eventID}", common.MakeFedAPI( "federation_invite", cfg.Matrix.ServerName, keys, @@ -78,13 +78,13 @@ func Setup( cfg, producer, keys, ) }, - )).Methods("PUT", "OPTIONS") + )).Methods(http.MethodPut, http.MethodOptions) v1fedmux.Handle("/3pid/onbind", common.MakeExternalAPI("3pid_onbind", func(req *http.Request) util.JSONResponse { return CreateInvitesFrom3PIDInvites(req, query, cfg, producer, federation, accountDB) }, - )).Methods("POST", "OPTIONS") + )).Methods(http.MethodPost, http.MethodOptions) v1fedmux.Handle("/exchange_third_party_invite/{roomID}", common.MakeFedAPI( "exchange_third_party_invite", cfg.Matrix.ServerName, keys, @@ -94,7 +94,7 @@ func Setup( httpReq, request, vars["roomID"], query, cfg, federation, producer, ) }, - )).Methods("PUT", "OPTIONS") + )).Methods(http.MethodPut, http.MethodOptions) v1fedmux.Handle("/event/{eventID}", common.MakeFedAPI( "federation_get_event", cfg.Matrix.ServerName, keys, @@ -104,7 +104,7 @@ func Setup( httpReq.Context(), request, cfg, query, time.Now(), keys, vars["eventID"], ) }, - )).Methods("GET") + )).Methods(http.MethodGet) v1fedmux.Handle("/query/directory/", common.MakeFedAPI( "federation_query_room_alias", cfg.Matrix.ServerName, keys, @@ -113,7 +113,7 @@ func Setup( httpReq, federation, cfg, aliasAPI, ) }, - )).Methods("GET") + )).Methods(http.MethodGet) v1fedmux.Handle("/query/profile", common.MakeFedAPI( "federation_query_profile", cfg.Matrix.ServerName, keys, @@ -122,7 +122,7 @@ func Setup( httpReq, accountDB, cfg, ) }, - )).Methods("GET") + )).Methods(http.MethodGet) v1fedmux.Handle("/make_join/{roomID}/{userID}", common.MakeFedAPI( "federation_make_join", cfg.Matrix.ServerName, keys, @@ -134,7 +134,7 @@ func Setup( httpReq.Context(), httpReq, request, cfg, query, roomID, userID, ) }, - )).Methods("GET") + )).Methods(http.MethodGet) v1fedmux.Handle("/send_join/{roomID}/{userID}", common.MakeFedAPI( "federation_send_join", cfg.Matrix.ServerName, keys, @@ -146,12 +146,12 @@ func Setup( httpReq.Context(), httpReq, request, cfg, query, producer, keys, roomID, userID, ) }, - )).Methods("PUT") + )).Methods(http.MethodPut) v1fedmux.Handle("/version", common.MakeExternalAPI( "federation_version", func(httpReq *http.Request) util.JSONResponse { return Version() }, - )).Methods("GET") + )).Methods(http.MethodGet) } diff --git a/src/github.com/matrix-org/dendrite/federationapi/routing/send.go b/src/github.com/matrix-org/dendrite/federationapi/routing/send.go index 4b6e8201a..c0c425f5e 100644 --- a/src/github.com/matrix-org/dendrite/federationapi/routing/send.go +++ b/src/github.com/matrix-org/dendrite/federationapi/routing/send.go @@ -50,7 +50,7 @@ func Send( } if err := json.Unmarshal(request.Content(), &t); err != nil { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.NotJSON("The request body could not be decoded into valid JSON. " + err.Error()), } } @@ -65,7 +65,7 @@ func Send( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: resp, } } diff --git a/src/github.com/matrix-org/dendrite/federationapi/routing/threepid.go b/src/github.com/matrix-org/dendrite/federationapi/routing/threepid.go index 6227d150d..8537002f1 100644 --- a/src/github.com/matrix-org/dendrite/federationapi/routing/threepid.go +++ b/src/github.com/matrix-org/dendrite/federationapi/routing/threepid.go @@ -86,7 +86,7 @@ func CreateInvitesFrom3PIDInvites( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct{}{}, } } @@ -104,7 +104,7 @@ func ExchangeThirdPartyInvite( var builder gomatrixserverlib.EventBuilder if err := json.Unmarshal(request.Content(), &builder); err != nil { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.NotJSON("The request body could not be decoded into valid JSON. " + err.Error()), } } @@ -112,7 +112,7 @@ func ExchangeThirdPartyInvite( // Check that the room ID is correct. if builder.RoomID != roomID { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("The room ID in the request path must match the room ID in the invite event JSON"), } } @@ -121,7 +121,7 @@ func ExchangeThirdPartyInvite( _, targetDomain, err := gomatrixserverlib.SplitID('@', *builder.StateKey) if err != nil { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("The event's state key isn't a Matrix user ID"), } } @@ -129,7 +129,7 @@ func ExchangeThirdPartyInvite( // Check that the target user is from the requesting homeserver. if targetDomain != request.Origin() { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("The event's state key doesn't have the same domain as the request's origin"), } } @@ -138,7 +138,7 @@ func ExchangeThirdPartyInvite( event, err := buildMembershipEvent(httpReq.Context(), &builder, queryAPI, cfg) if err == errNotInRoom { return util.JSONResponse{ - Code: 404, + Code: http.StatusNotFound, JSON: jsonerror.NotFound("Unknown room " + roomID), } } else if err != nil { @@ -160,7 +160,7 @@ func ExchangeThirdPartyInvite( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct{}{}, } } diff --git a/src/github.com/matrix-org/dendrite/federationapi/routing/version.go b/src/github.com/matrix-org/dendrite/federationapi/routing/version.go index 082af533e..14ecd21e1 100644 --- a/src/github.com/matrix-org/dendrite/federationapi/routing/version.go +++ b/src/github.com/matrix-org/dendrite/federationapi/routing/version.go @@ -15,6 +15,8 @@ package routing import ( + "net/http" + "github.com/matrix-org/util" ) @@ -29,5 +31,5 @@ type server struct { // Version returns the server version func Version() util.JSONResponse { - return util.JSONResponse{Code: 200, JSON: &version{server{"dev", "Dendrite"}}} + return util.JSONResponse{Code: http.StatusOK, JSON: &version{server{"dev", "Dendrite"}}} } diff --git a/src/github.com/matrix-org/dendrite/mediaapi/routing/download.go b/src/github.com/matrix-org/dendrite/mediaapi/routing/download.go index 2ce2993f8..9c8f43c44 100644 --- a/src/github.com/matrix-org/dendrite/mediaapi/routing/download.go +++ b/src/github.com/matrix-org/dendrite/mediaapi/routing/download.go @@ -107,9 +107,9 @@ func Download( } // request validation - if req.Method != "GET" { + if req.Method != http.MethodGet { dReq.jsonErrorResponse(w, util.JSONResponse{ - Code: 405, + Code: http.StatusMethodNotAllowed, JSON: jsonerror.Unknown("request method must be GET"), }) return @@ -132,7 +132,7 @@ func Download( if metadata == nil { dReq.jsonErrorResponse(w, util.JSONResponse{ - Code: 404, + Code: http.StatusNotFound, JSON: jsonerror.NotFound("File not found"), }) return @@ -146,7 +146,7 @@ func (r *downloadRequest) jsonErrorResponse(w http.ResponseWriter, res util.JSON if err != nil { r.Logger.WithError(err).Error("Failed to marshal JSONResponse") // this should never fail to be marshalled so drop err to the floor - res = util.MessageResponse(500, "Internal Server Error") + res = util.MessageResponse(http.StatusInternalServerError, "Internal Server Error") resBytes, _ = json.Marshal(res.JSON) } @@ -162,7 +162,7 @@ func (r *downloadRequest) jsonErrorResponse(w http.ResponseWriter, res util.JSON func (r *downloadRequest) Validate() *util.JSONResponse { if !mediaIDRegex.MatchString(string(r.MediaMetadata.MediaID)) { return &util.JSONResponse{ - Code: 404, + Code: http.StatusNotFound, JSON: jsonerror.NotFound(fmt.Sprintf("mediaId must be a non-empty string using only characters in %v", mediaIDCharacters)), } } @@ -170,7 +170,7 @@ func (r *downloadRequest) Validate() *util.JSONResponse { // or by a DNS SRV record lookup when creating a request for remote files if r.MediaMetadata.Origin == "" { return &util.JSONResponse{ - Code: 404, + Code: http.StatusNotFound, JSON: jsonerror.NotFound("serverName must be a non-empty string"), } } @@ -178,7 +178,7 @@ func (r *downloadRequest) Validate() *util.JSONResponse { if r.IsThumbnailRequest { if r.ThumbnailSize.Width <= 0 || r.ThumbnailSize.Height <= 0 { return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.Unknown("width and height must be greater than 0"), } } @@ -188,7 +188,7 @@ func (r *downloadRequest) Validate() *util.JSONResponse { } if r.ThumbnailSize.ResizeMethod != types.Crop && r.ThumbnailSize.ResizeMethod != types.Scale { return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.Unknown("method must be one of crop or scale"), } } @@ -685,8 +685,8 @@ func (r *downloadRequest) createRemoteRequest( return nil, fmt.Errorf("file with media ID %q could not be downloaded from %q", r.MediaMetadata.MediaID, r.MediaMetadata.Origin) } - if resp.StatusCode != 200 { - if resp.StatusCode == 404 { + if resp.StatusCode != http.StatusOK { + if resp.StatusCode == http.StatusNotFound { return nil, nil } r.Logger.WithFields(log.Fields{ diff --git a/src/github.com/matrix-org/dendrite/mediaapi/routing/routing.go b/src/github.com/matrix-org/dendrite/mediaapi/routing/routing.go index 608136f49..852bb4d85 100644 --- a/src/github.com/matrix-org/dendrite/mediaapi/routing/routing.go +++ b/src/github.com/matrix-org/dendrite/mediaapi/routing/routing.go @@ -52,17 +52,17 @@ func Setup( func(req *http.Request, _ *authtypes.Device) util.JSONResponse { return Upload(req, cfg, db, activeThumbnailGeneration) }, - )).Methods("POST", "OPTIONS") + )).Methods(http.MethodPost, http.MethodOptions) activeRemoteRequests := &types.ActiveRemoteRequests{ MXCToResult: map[string]*types.RemoteRequestResult{}, } r0mux.Handle("/download/{serverName}/{mediaId}", makeDownloadAPI("download", cfg, db, client, activeRemoteRequests, activeThumbnailGeneration), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) r0mux.Handle("/thumbnail/{serverName}/{mediaId}", makeDownloadAPI("thumbnail", cfg, db, client, activeRemoteRequests, activeThumbnailGeneration), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) } func makeDownloadAPI( diff --git a/src/github.com/matrix-org/dendrite/mediaapi/routing/upload.go b/src/github.com/matrix-org/dendrite/mediaapi/routing/upload.go index 46eb242d8..1051e0e03 100644 --- a/src/github.com/matrix-org/dendrite/mediaapi/routing/upload.go +++ b/src/github.com/matrix-org/dendrite/mediaapi/routing/upload.go @@ -64,7 +64,7 @@ func Upload(req *http.Request, cfg *config.Dendrite, db *storage.Database, activ } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: uploadResponse{ ContentURI: fmt.Sprintf("mxc://%s/%s", cfg.Matrix.ServerName, r.MediaMetadata.MediaID), }, @@ -75,9 +75,9 @@ func Upload(req *http.Request, cfg *config.Dendrite, db *storage.Database, activ // all the metadata about the media being uploaded. // Returns either an uploadRequest or an error formatted as a util.JSONResponse func parseAndValidateRequest(req *http.Request, cfg *config.Dendrite) (*uploadRequest, *util.JSONResponse) { - if req.Method != "POST" { + if req.Method != http.MethodPost { return nil, &util.JSONResponse{ - Code: 405, + Code: http.StatusMethodNotAllowed, JSON: jsonerror.Unknown("HTTP request method must be POST."), } } @@ -123,7 +123,7 @@ func (r *uploadRequest) doUpload( }).Warn("Error while transferring file") fileutils.RemoveDir(tmpDir, r.Logger) return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.Unknown("Failed to upload"), } } @@ -155,7 +155,7 @@ func (r *uploadRequest) doUpload( r.MediaMetadata = mediaMetadata fileutils.RemoveDir(tmpDir, r.Logger) return &util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: uploadResponse{ ContentURI: fmt.Sprintf("mxc://%s/%s", cfg.Matrix.ServerName, r.MediaMetadata.MediaID), }, @@ -172,26 +172,26 @@ func (r *uploadRequest) doUpload( func (r *uploadRequest) Validate(maxFileSizeBytes config.FileSizeBytes) *util.JSONResponse { if r.MediaMetadata.FileSizeBytes < 1 { return &util.JSONResponse{ - Code: 411, + Code: http.StatusLengthRequired, JSON: jsonerror.Unknown("HTTP Content-Length request header must be greater than zero."), } } if maxFileSizeBytes > 0 && r.MediaMetadata.FileSizeBytes > types.FileSizeBytes(maxFileSizeBytes) { return &util.JSONResponse{ - Code: 413, + Code: http.StatusRequestEntityTooLarge, JSON: jsonerror.Unknown(fmt.Sprintf("HTTP Content-Length is greater than the maximum allowed upload size (%v).", maxFileSizeBytes)), } } // TODO: Check if the Content-Type is a valid type? if r.MediaMetadata.ContentType == "" { return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.Unknown("HTTP Content-Type request header must be set."), } } if strings.HasPrefix(string(r.MediaMetadata.UploadName), "~") { return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.Unknown("File name must not begin with '~'."), } } @@ -204,7 +204,7 @@ func (r *uploadRequest) Validate(maxFileSizeBytes config.FileSizeBytes) *util.JS // https://github.com/matrix-org/synapse/blob/v0.19.2/synapse/types.py#L92 if _, _, err := gomatrixserverlib.SplitID('@', string(r.MediaMetadata.UserID)); err != nil { return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.BadJSON("user id must be in the form @localpart:domain"), } } @@ -230,7 +230,7 @@ func (r *uploadRequest) storeFileAndMetadata( if err != nil { r.Logger.WithError(err).Error("Failed to move file.") return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.Unknown("Failed to upload"), } } @@ -247,7 +247,7 @@ func (r *uploadRequest) storeFileAndMetadata( fileutils.RemoveDir(types.Path(path.Dir(string(finalPath))), r.Logger) } return &util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.Unknown("Failed to upload"), } } diff --git a/src/github.com/matrix-org/dendrite/publicroomsapi/directory/directory.go b/src/github.com/matrix-org/dendrite/publicroomsapi/directory/directory.go index 8c6de95b3..bb0153850 100644 --- a/src/github.com/matrix-org/dendrite/publicroomsapi/directory/directory.go +++ b/src/github.com/matrix-org/dendrite/publicroomsapi/directory/directory.go @@ -45,7 +45,7 @@ func GetVisibility( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: v, } } @@ -67,7 +67,7 @@ func SetVisibility( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: struct{}{}, } } diff --git a/src/github.com/matrix-org/dendrite/publicroomsapi/directory/public_rooms.go b/src/github.com/matrix-org/dendrite/publicroomsapi/directory/public_rooms.go index 772c0f6bf..100e28e9b 100644 --- a/src/github.com/matrix-org/dendrite/publicroomsapi/directory/public_rooms.go +++ b/src/github.com/matrix-org/dendrite/publicroomsapi/directory/public_rooms.go @@ -82,7 +82,7 @@ func GetPublicRooms( } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: response, } } @@ -90,7 +90,7 @@ func GetPublicRooms( // fillPublicRoomsReq fills the Limit, Since and Filter attributes of a GET or POST request // on /publicRooms by parsing the incoming HTTP request func fillPublicRoomsReq(httpReq *http.Request, request *publicRoomReq) *util.JSONResponse { - if httpReq.Method == "GET" { + if httpReq.Method == http.MethodGet { limit, err := strconv.Atoi(httpReq.FormValue("limit")) // Atoi returns 0 and an error when trying to parse an empty string // In that case, we want to assign 0 so we ignore the error @@ -101,12 +101,12 @@ func fillPublicRoomsReq(httpReq *http.Request, request *publicRoomReq) *util.JSO request.Limit = int16(limit) request.Since = httpReq.FormValue("since") return nil - } else if httpReq.Method == "POST" { + } else if httpReq.Method == http.MethodPost { return httputil.UnmarshalJSONRequest(httpReq, request) } return &util.JSONResponse{ - Code: 405, + Code: http.StatusMethodNotAllowed, JSON: jsonerror.NotFound("Bad method"), } } diff --git a/src/github.com/matrix-org/dendrite/publicroomsapi/routing/routing.go b/src/github.com/matrix-org/dendrite/publicroomsapi/routing/routing.go index 6270b311f..34cecc20c 100644 --- a/src/github.com/matrix-org/dendrite/publicroomsapi/routing/routing.go +++ b/src/github.com/matrix-org/dendrite/publicroomsapi/routing/routing.go @@ -36,16 +36,16 @@ func Setup(apiMux *mux.Router, deviceDB *devices.Database, publicRoomsDB *storag vars := mux.Vars(req) return directory.GetVisibility(req, publicRoomsDB, vars["roomID"]) }), - ).Methods("GET", "OPTIONS") + ).Methods(http.MethodGet, http.MethodOptions) r0mux.Handle("/directory/list/room/{roomID}", common.MakeAuthAPI("directory_list", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) return directory.SetVisibility(req, publicRoomsDB, vars["roomID"]) }), - ).Methods("PUT", "OPTIONS") + ).Methods(http.MethodPut, http.MethodOptions) r0mux.Handle("/publicRooms", common.MakeExternalAPI("public_rooms", func(req *http.Request) util.JSONResponse { return directory.GetPublicRooms(req, publicRoomsDB) }), - ).Methods("GET", "POST", "OPTIONS") + ).Methods(http.MethodGet, http.MethodPost, http.MethodOptions) } diff --git a/src/github.com/matrix-org/dendrite/roomserver/alias/alias.go b/src/github.com/matrix-org/dendrite/roomserver/alias/alias.go index 7f41b4629..1b0c0fdc7 100644 --- a/src/github.com/matrix-org/dendrite/roomserver/alias/alias.go +++ b/src/github.com/matrix-org/dendrite/roomserver/alias/alias.go @@ -225,7 +225,7 @@ func (r *RoomserverAliasAPI) SetupHTTP(servMux *http.ServeMux) { if err := r.SetRoomAlias(req.Context(), &request, &response); err != nil { return util.ErrorResponse(err) } - return util.JSONResponse{Code: 200, JSON: &response} + return util.JSONResponse{Code: http.StatusOK, JSON: &response} }), ) servMux.Handle( @@ -239,7 +239,7 @@ func (r *RoomserverAliasAPI) SetupHTTP(servMux *http.ServeMux) { if err := r.GetAliasRoomID(req.Context(), &request, &response); err != nil { return util.ErrorResponse(err) } - return util.JSONResponse{Code: 200, JSON: &response} + return util.JSONResponse{Code: http.StatusOK, JSON: &response} }), ) servMux.Handle( @@ -253,7 +253,7 @@ func (r *RoomserverAliasAPI) SetupHTTP(servMux *http.ServeMux) { if err := r.RemoveRoomAlias(req.Context(), &request, &response); err != nil { return util.ErrorResponse(err) } - return util.JSONResponse{Code: 200, JSON: &response} + return util.JSONResponse{Code: http.StatusOK, JSON: &response} }), ) } diff --git a/src/github.com/matrix-org/dendrite/roomserver/api/query.go b/src/github.com/matrix-org/dendrite/roomserver/api/query.go index f23fd3b87..aea7facef 100644 --- a/src/github.com/matrix-org/dendrite/roomserver/api/query.go +++ b/src/github.com/matrix-org/dendrite/roomserver/api/query.go @@ -21,10 +21,9 @@ import ( "fmt" "net/http" + opentracing "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" - "github.com/opentracing/opentracing-go" - "github.com/matrix-org/gomatrixserverlib" ) @@ -371,7 +370,7 @@ func postJSON( return err } - req, err := http.NewRequest("POST", apiURL, bytes.NewReader(jsonBytes)) + req, err := http.NewRequest(http.MethodPost, apiURL, bytes.NewReader(jsonBytes)) if err != nil { return err } @@ -394,7 +393,7 @@ func postJSON( if err != nil { return err } - if res.StatusCode != 200 { + if res.StatusCode != http.StatusOK { var errorBody struct { Message string `json:"message"` } diff --git a/src/github.com/matrix-org/dendrite/roomserver/input/input.go b/src/github.com/matrix-org/dendrite/roomserver/input/input.go index 4d5848f4c..98971bf8e 100644 --- a/src/github.com/matrix-org/dendrite/roomserver/input/input.go +++ b/src/github.com/matrix-org/dendrite/roomserver/input/input.go @@ -84,12 +84,12 @@ func (r *RoomserverInputAPI) SetupHTTP(servMux *http.ServeMux) { var request api.InputRoomEventsRequest var response api.InputRoomEventsResponse if err := json.NewDecoder(req.Body).Decode(&request); err != nil { - return util.MessageResponse(400, err.Error()) + return util.MessageResponse(http.StatusBadRequest, err.Error()) } if err := r.InputRoomEvents(req.Context(), &request, &response); err != nil { return util.ErrorResponse(err) } - return util.JSONResponse{Code: 200, JSON: &response} + return util.JSONResponse{Code: http.StatusOK, JSON: &response} }), ) } diff --git a/src/github.com/matrix-org/dendrite/roomserver/query/query.go b/src/github.com/matrix-org/dendrite/roomserver/query/query.go index 284327879..bc8a3d22e 100644 --- a/src/github.com/matrix-org/dendrite/roomserver/query/query.go +++ b/src/github.com/matrix-org/dendrite/roomserver/query/query.go @@ -534,7 +534,7 @@ func (r *RoomserverQueryAPI) SetupHTTP(servMux *http.ServeMux) { if err := r.QueryLatestEventsAndState(req.Context(), &request, &response); err != nil { return util.ErrorResponse(err) } - return util.JSONResponse{Code: 200, JSON: &response} + return util.JSONResponse{Code: http.StatusOK, JSON: &response} }), ) servMux.Handle( @@ -548,7 +548,7 @@ func (r *RoomserverQueryAPI) SetupHTTP(servMux *http.ServeMux) { if err := r.QueryStateAfterEvents(req.Context(), &request, &response); err != nil { return util.ErrorResponse(err) } - return util.JSONResponse{Code: 200, JSON: &response} + return util.JSONResponse{Code: http.StatusOK, JSON: &response} }), ) servMux.Handle( @@ -562,7 +562,7 @@ func (r *RoomserverQueryAPI) SetupHTTP(servMux *http.ServeMux) { if err := r.QueryEventsByID(req.Context(), &request, &response); err != nil { return util.ErrorResponse(err) } - return util.JSONResponse{Code: 200, JSON: &response} + return util.JSONResponse{Code: http.StatusOK, JSON: &response} }), ) servMux.Handle( @@ -576,7 +576,7 @@ func (r *RoomserverQueryAPI) SetupHTTP(servMux *http.ServeMux) { if err := r.QueryMembershipsForRoom(req.Context(), &request, &response); err != nil { return util.ErrorResponse(err) } - return util.JSONResponse{Code: 200, JSON: &response} + return util.JSONResponse{Code: http.StatusOK, JSON: &response} }), ) servMux.Handle( @@ -590,7 +590,7 @@ func (r *RoomserverQueryAPI) SetupHTTP(servMux *http.ServeMux) { if err := r.QueryInvitesForUser(req.Context(), &request, &response); err != nil { return util.ErrorResponse(err) } - return util.JSONResponse{Code: 200, JSON: &response} + return util.JSONResponse{Code: http.StatusOK, JSON: &response} }), ) servMux.Handle( @@ -604,7 +604,7 @@ func (r *RoomserverQueryAPI) SetupHTTP(servMux *http.ServeMux) { if err := r.QueryServerAllowedToSeeEvent(req.Context(), &request, &response); err != nil { return util.ErrorResponse(err) } - return util.JSONResponse{Code: 200, JSON: &response} + return util.JSONResponse{Code: http.StatusOK, JSON: &response} }), ) servMux.Handle( @@ -618,7 +618,7 @@ func (r *RoomserverQueryAPI) SetupHTTP(servMux *http.ServeMux) { if err := r.QueryStateAndAuthChain(req.Context(), &request, &response); err != nil { return util.ErrorResponse(err) } - return util.JSONResponse{Code: 200, JSON: &response} + return util.JSONResponse{Code: http.StatusOK, JSON: &response} }), ) } diff --git a/src/github.com/matrix-org/dendrite/syncapi/routing/routing.go b/src/github.com/matrix-org/dendrite/syncapi/routing/routing.go index c080c8521..e5a906b08 100644 --- a/src/github.com/matrix-org/dendrite/syncapi/routing/routing.go +++ b/src/github.com/matrix-org/dendrite/syncapi/routing/routing.go @@ -34,20 +34,20 @@ func Setup(apiMux *mux.Router, srp *sync.RequestPool, syncDB *storage.SyncServer r0mux.Handle("/sync", common.MakeAuthAPI("sync", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { return srp.OnIncomingSyncRequest(req, device) - })).Methods("GET", "OPTIONS") + })).Methods(http.MethodGet, http.MethodOptions) r0mux.Handle("/rooms/{roomID}/state", common.MakeAuthAPI("room_state", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) return OnIncomingStateRequest(req, syncDB, vars["roomID"]) - })).Methods("GET", "OPTIONS") + })).Methods(http.MethodGet, http.MethodOptions) r0mux.Handle("/rooms/{roomID}/state/{type}", common.MakeAuthAPI("room_state", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) return OnIncomingStateTypeRequest(req, syncDB, vars["roomID"], vars["type"], "") - })).Methods("GET", "OPTIONS") + })).Methods(http.MethodGet, http.MethodOptions) r0mux.Handle("/rooms/{roomID}/state/{type}/{stateKey}", common.MakeAuthAPI("room_state", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { vars := mux.Vars(req) return OnIncomingStateTypeRequest(req, syncDB, vars["roomID"], vars["type"], vars["stateKey"]) - })).Methods("GET", "OPTIONS") + })).Methods(http.MethodGet, http.MethodOptions) } diff --git a/src/github.com/matrix-org/dendrite/syncapi/routing/state.go b/src/github.com/matrix-org/dendrite/syncapi/routing/state.go index 6c825fce8..6b98a0b7b 100644 --- a/src/github.com/matrix-org/dendrite/syncapi/routing/state.go +++ b/src/github.com/matrix-org/dendrite/syncapi/routing/state.go @@ -75,7 +75,7 @@ func OnIncomingStateRequest(req *http.Request, db *storage.SyncServerDatabase, r } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: resp, } } @@ -102,7 +102,7 @@ func OnIncomingStateTypeRequest(req *http.Request, db *storage.SyncServerDatabas if event == nil { return util.JSONResponse{ - Code: 404, + Code: http.StatusNotFound, JSON: jsonerror.NotFound("cannot find state"), } } @@ -112,7 +112,7 @@ func OnIncomingStateTypeRequest(req *http.Request, db *storage.SyncServerDatabas } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: stateEvent.Content, } } diff --git a/src/github.com/matrix-org/dendrite/syncapi/sync/requestpool.go b/src/github.com/matrix-org/dendrite/syncapi/sync/requestpool.go index 703ddd3f1..5c560ff52 100644 --- a/src/github.com/matrix-org/dendrite/syncapi/sync/requestpool.go +++ b/src/github.com/matrix-org/dendrite/syncapi/sync/requestpool.go @@ -51,7 +51,7 @@ func (rp *RequestPool) OnIncomingSyncRequest(req *http.Request, device *authtype syncReq, err := newSyncRequest(req, *device) if err != nil { return util.JSONResponse{ - Code: 400, + Code: http.StatusBadRequest, JSON: jsonerror.Unknown(err.Error()), } } @@ -70,7 +70,7 @@ func (rp *RequestPool) OnIncomingSyncRequest(req *http.Request, device *authtype return httputil.LogThenError(req, err) } return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: syncData, } } @@ -92,7 +92,7 @@ func (rp *RequestPool) OnIncomingSyncRequest(req *http.Request, device *authtype // Or for timeout to expire case <-timer.C: return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: types.NewResponse(currPos), } // Or for the request to be cancelled @@ -111,7 +111,7 @@ func (rp *RequestPool) OnIncomingSyncRequest(req *http.Request, device *authtype } if !syncData.IsEmpty() { return util.JSONResponse{ - Code: 200, + Code: http.StatusOK, JSON: syncData, } }