Use http.Status* and http.Method* where appropriate (#417)

Signed-off-by: Scott Raine <me@nylar.io>
main
Scott Raine 2018-03-13 11:55:45 -04:00 committed by Richard van der Hoff
parent f12ffb660d
commit c9add39768
45 changed files with 308 additions and 305 deletions

View File

@ -50,7 +50,7 @@ func VerifyAccessToken(req *http.Request, deviceDB DeviceDatabase) (device *auth
token, err := extractAccessToken(req) token, err := extractAccessToken(req)
if err != nil { if err != nil {
resErr = &util.JSONResponse{ resErr = &util.JSONResponse{
Code: 401, Code: http.StatusUnauthorized,
JSON: jsonerror.MissingToken(err.Error()), JSON: jsonerror.MissingToken(err.Error()),
} }
return return
@ -59,7 +59,7 @@ func VerifyAccessToken(req *http.Request, deviceDB DeviceDatabase) (device *auth
if err != nil { if err != nil {
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
resErr = &util.JSONResponse{ resErr = &util.JSONResponse{
Code: 401, Code: http.StatusUnauthorized,
JSON: jsonerror.UnknownToken("Unknown token"), JSON: jsonerror.UnknownToken("Unknown token"),
} }
} else { } else {

View File

@ -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 // debugging because an error will be produced for both invalid/malformed JSON AND
// valid JSON with incorrect types for values. // valid JSON with incorrect types for values.
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The request body could not be decoded into valid JSON. " + err.Error()), JSON: jsonerror.BadJSON("The request body could not be decoded into valid JSON. " + err.Error()),
} }
} }

View File

@ -16,6 +16,7 @@ package jsonerror
import ( import (
"fmt" "fmt"
"net/http"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -35,7 +36,7 @@ func (e *MatrixError) Error() string {
// format. // format.
func InternalServerError() util.JSONResponse { func InternalServerError() util.JSONResponse {
return util.JSONResponse{ return util.JSONResponse{
Code: 500, Code: http.StatusInternalServerError,
JSON: Unknown("Internal Server Error"), JSON: Unknown("Internal Server Error"),
} }
} }

View File

@ -33,16 +33,16 @@ func SaveAccountData(
req *http.Request, accountDB *accounts.Database, device *authtypes.Device, req *http.Request, accountDB *accounts.Database, device *authtypes.Device,
userID string, roomID string, dataType string, syncProducer *producers.SyncAPIProducer, userID string, roomID string, dataType string, syncProducer *producers.SyncAPIProducer,
) util.JSONResponse { ) util.JSONResponse {
if req.Method != "PUT" { if req.Method != http.MethodPut {
return util.JSONResponse{ return util.JSONResponse{
Code: 405, Code: http.StatusMethodNotAllowed,
JSON: jsonerror.NotFound("Bad method"), JSON: jsonerror.NotFound("Bad method"),
} }
} }
if userID != device.UserID { if userID != device.UserID {
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("userID does not match the current user"), JSON: jsonerror.Forbidden("userID does not match the current user"),
} }
} }
@ -70,7 +70,7 @@ func SaveAccountData(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
} }
} }

View File

@ -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. // 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+":") { if strings.ContainsAny(r.RoomAliasName, whitespace+":") {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("room_alias_name cannot contain whitespace"), 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 // https://github.com/matrix-org/synapse/blob/v0.19.2/synapse/types.py#L92
if _, _, err := gomatrixserverlib.SplitID('@', userID); err != nil { if _, _, err := gomatrixserverlib.SplitID('@', userID); err != nil {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("user id must be in the form @localpart:domain"), JSON: jsonerror.BadJSON("user id must be in the form @localpart:domain"),
} }
} }
@ -92,7 +92,7 @@ func (r createRoomRequest) Validate() *util.JSONResponse {
break break
default: default:
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("preset must be any of 'private_chat', 'trusted_private_chat', 'public_chat'"), JSON: jsonerror.BadJSON("preset must be any of 'private_chat', 'trusted_private_chat', 'public_chat'"),
} }
} }

View File

@ -54,7 +54,7 @@ func GetDeviceByID(
dev, err := deviceDB.GetDeviceByID(ctx, localpart, deviceID) dev, err := deviceDB.GetDeviceByID(ctx, localpart, deviceID)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Unknown device"), JSON: jsonerror.NotFound("Unknown device"),
} }
} else if err != nil { } else if err != nil {
@ -62,7 +62,7 @@ func GetDeviceByID(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: deviceJSON{ JSON: deviceJSON{
DeviceID: dev.ID, DeviceID: dev.ID,
UserID: dev.UserID, UserID: dev.UserID,
@ -96,7 +96,7 @@ func GetDevicesByLocalpart(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: res, JSON: res,
} }
} }
@ -106,9 +106,9 @@ func UpdateDeviceByID(
req *http.Request, deviceDB *devices.Database, device *authtypes.Device, req *http.Request, deviceDB *devices.Database, device *authtypes.Device,
deviceID string, deviceID string,
) util.JSONResponse { ) util.JSONResponse {
if req.Method != "PUT" { if req.Method != http.MethodPut {
return util.JSONResponse{ return util.JSONResponse{
Code: 405, Code: http.StatusMethodNotAllowed,
JSON: jsonerror.NotFound("Bad Method"), JSON: jsonerror.NotFound("Bad Method"),
} }
} }
@ -122,7 +122,7 @@ func UpdateDeviceByID(
dev, err := deviceDB.GetDeviceByID(ctx, localpart, deviceID) dev, err := deviceDB.GetDeviceByID(ctx, localpart, deviceID)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Unknown device"), JSON: jsonerror.NotFound("Unknown device"),
} }
} else if err != nil { } else if err != nil {
@ -131,7 +131,7 @@ func UpdateDeviceByID(
if dev.UserID != device.UserID { if dev.UserID != device.UserID {
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("device not owned by current user"), JSON: jsonerror.Forbidden("device not owned by current user"),
} }
} }
@ -149,7 +149,7 @@ func UpdateDeviceByID(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
} }
} }

View File

@ -38,7 +38,7 @@ func DirectoryRoom(
_, domain, err := gomatrixserverlib.SplitID('#', roomAlias) _, domain, err := gomatrixserverlib.SplitID('#', roomAlias)
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Room alias must be in the form '#localpart:domain'"), JSON: jsonerror.BadJSON("Room alias must be in the form '#localpart:domain'"),
} }
} }
@ -61,7 +61,7 @@ func DirectoryRoom(
} else { } else {
// If the response doesn't contain a non-empty string, return an error // If the response doesn't contain a non-empty string, return an error
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Room alias " + roomAlias + " not found."), JSON: jsonerror.NotFound("Room alias " + roomAlias + " not found."),
} }
} }
@ -70,9 +70,9 @@ func DirectoryRoom(
if err != nil { if err != nil {
switch x := err.(type) { switch x := err.(type) {
case gomatrix.HTTPError: case gomatrix.HTTPError:
if x.Code == 404 { if x.Code == http.StatusNotFound {
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Room alias not found"), JSON: jsonerror.NotFound("Room alias not found"),
} }
} }
@ -84,7 +84,7 @@ func DirectoryRoom(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: resp, JSON: resp,
} }
} }
@ -101,14 +101,14 @@ func SetLocalAlias(
_, domain, err := gomatrixserverlib.SplitID('#', alias) _, domain, err := gomatrixserverlib.SplitID('#', alias)
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Room alias must be in the form '#localpart:domain'"), JSON: jsonerror.BadJSON("Room alias must be in the form '#localpart:domain'"),
} }
} }
if domain != cfg.Matrix.ServerName { if domain != cfg.Matrix.ServerName {
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Alias must be on local homeserver"), JSON: jsonerror.Forbidden("Alias must be on local homeserver"),
} }
} }
@ -132,13 +132,13 @@ func SetLocalAlias(
if queryRes.AliasExists { if queryRes.AliasExists {
return util.JSONResponse{ return util.JSONResponse{
Code: 409, Code: http.StatusConflict,
JSON: jsonerror.Unknown("The alias " + alias + " already exists."), JSON: jsonerror.Unknown("The alias " + alias + " already exists."),
} }
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
} }
} }
@ -161,7 +161,7 @@ func RemoveLocalAlias(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
} }
} }

View File

@ -34,13 +34,13 @@ func GetFilter(
) util.JSONResponse { ) util.JSONResponse {
if req.Method != http.MethodGet { if req.Method != http.MethodGet {
return util.JSONResponse{ return util.JSONResponse{
Code: 405, Code: http.StatusMethodNotAllowed,
JSON: jsonerror.NotFound("Bad method"), JSON: jsonerror.NotFound("Bad method"),
} }
} }
if userID != device.UserID { if userID != device.UserID {
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Cannot get filters for other users"), 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, // but if there are obscure db errors, this will also be returned,
// even though it is not correct. // even though it is not correct.
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.NotFound("No such filter"), JSON: jsonerror.NotFound("No such filter"),
} }
} }
@ -66,7 +66,7 @@ func GetFilter(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: filter, JSON: filter,
} }
} }
@ -81,13 +81,13 @@ func PutFilter(
) util.JSONResponse { ) util.JSONResponse {
if req.Method != http.MethodPost { if req.Method != http.MethodPost {
return util.JSONResponse{ return util.JSONResponse{
Code: 405, Code: http.StatusMethodNotAllowed,
JSON: jsonerror.NotFound("Bad method"), JSON: jsonerror.NotFound("Bad method"),
} }
} }
if userID != device.UserID { if userID != device.UserID {
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Cannot create filters for other users"), JSON: jsonerror.Forbidden("Cannot create filters for other users"),
} }
} }
@ -106,7 +106,7 @@ func PutFilter(
filterArray, err := json.Marshal(filter) filterArray, err := json.Marshal(filter)
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Filter is malformed"), JSON: jsonerror.BadJSON("Filter is malformed"),
} }
} }
@ -117,7 +117,7 @@ func PutFilter(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: filterResponse{FilterID: filterID}, JSON: filterResponse{FilterID: filterID},
} }
} }

View File

@ -75,7 +75,7 @@ func JoinRoomByIDOrAlias(
return r.joinRoomByAlias(roomIDOrAlias) return r.joinRoomByAlias(roomIDOrAlias)
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Invalid first character for room ID or alias"), 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 // joinRoomUsingServers passing an empty list since joinRoomUserServers
// will check if we are already in the room first. // will check if we are already in the room first.
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("You are not invited to the room"), 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) _, domain, err := gomatrixserverlib.SplitID('#', roomAlias)
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Room alias must be in the form '#localpart:domain'"), 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 // If the response doesn't contain a non-empty string, return an error
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Room alias " + roomAlias + " not found."), JSON: jsonerror.NotFound("Room alias " + roomAlias + " not found."),
} }
} }
@ -171,9 +171,9 @@ func (r joinRoomReq) joinRoomByRemoteAlias(
if err != nil { if err != nil {
switch x := err.(type) { switch x := err.(type) {
case gomatrix.HTTPError: case gomatrix.HTTPError:
if x.Code == 404 { if x.Code == http.StatusNotFound {
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Room alias not found"), JSON: jsonerror.NotFound("Room alias not found"),
} }
} }
@ -221,7 +221,7 @@ func (r joinRoomReq) joinRoomUsingServers(
return httputil.LogThenError(r.req, err) return httputil.LogThenError(r.req, err)
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct { JSON: struct {
RoomID string `json:"room_id"` RoomID string `json:"room_id"`
}{roomID}, }{roomID},
@ -233,7 +233,7 @@ func (r joinRoomReq) joinRoomUsingServers(
if len(servers) == 0 { if len(servers) == 0 {
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("No candidate servers found for room"), JSON: jsonerror.NotFound("No candidate servers found for room"),
} }
} }
@ -312,7 +312,7 @@ func (r joinRoomReq) joinRoomUsingServer(roomID string, server gomatrixserverlib
} }
return &util.JSONResponse{ return &util.JSONResponse{
Code: 200, Code: http.StatusOK,
// TODO: Put the response struct somewhere common. // TODO: Put the response struct somewhere common.
JSON: struct { JSON: struct {
RoomID string `json:"room_id"` RoomID string `json:"room_id"`

View File

@ -62,12 +62,12 @@ func Login(
req *http.Request, accountDB *accounts.Database, deviceDB *devices.Database, req *http.Request, accountDB *accounts.Database, deviceDB *devices.Database,
cfg config.Dendrite, cfg config.Dendrite,
) util.JSONResponse { ) 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{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: passwordLogin(), JSON: passwordLogin(),
} }
} else if req.Method == "POST" { } else if req.Method == http.MethodPost {
var r passwordRequest var r passwordRequest
resErr := httputil.UnmarshalJSONRequest(req, &r) resErr := httputil.UnmarshalJSONRequest(req, &r)
if resErr != nil { if resErr != nil {
@ -75,7 +75,7 @@ func Login(
} }
if r.User == "" { if r.User == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("'user' must be supplied."), JSON: jsonerror.BadJSON("'user' must be supplied."),
} }
} }
@ -90,14 +90,14 @@ func Login(
localpart, domain, err = gomatrixserverlib.SplitID('@', r.User) localpart, domain, err = gomatrixserverlib.SplitID('@', r.User)
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidUsername("Invalid username"), JSON: jsonerror.InvalidUsername("Invalid username"),
} }
} }
if domain != cfg.Matrix.ServerName { if domain != cfg.Matrix.ServerName {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidUsername("User ID not ours"), 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 // 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. // but that would leak the existence of the user.
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("username or password was incorrect, or the account does not exist"), JSON: jsonerror.Forbidden("username or password was incorrect, or the account does not exist"),
} }
} }
@ -124,13 +124,13 @@ func Login(
) )
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 500, Code: http.StatusInternalServerError,
JSON: jsonerror.Unknown("failed to create device: " + err.Error()), JSON: jsonerror.Unknown("failed to create device: " + err.Error()),
} }
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: loginResponse{ JSON: loginResponse{
UserID: dev.UserID, UserID: dev.UserID,
AccessToken: dev.AccessToken, AccessToken: dev.AccessToken,
@ -140,7 +140,7 @@ func Login(
} }
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 405, Code: http.StatusMethodNotAllowed,
JSON: jsonerror.NotFound("Bad method"), JSON: jsonerror.NotFound("Bad method"),
} }
} }

View File

@ -29,9 +29,9 @@ import (
func Logout( func Logout(
req *http.Request, deviceDB *devices.Database, device *authtypes.Device, req *http.Request, deviceDB *devices.Database, device *authtypes.Device,
) util.JSONResponse { ) util.JSONResponse {
if req.Method != "POST" { if req.Method != http.MethodPost {
return util.JSONResponse{ return util.JSONResponse{
Code: 405, Code: http.StatusMethodNotAllowed,
JSON: jsonerror.NotFound("Bad method"), JSON: jsonerror.NotFound("Bad method"),
} }
} }
@ -46,7 +46,7 @@ func Logout(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
} }
} }
@ -65,7 +65,7 @@ func LogoutAll(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
} }
} }

View File

@ -53,17 +53,17 @@ func SendMembership(
) )
if err == threepid.ErrMissingParameter { if err == threepid.ErrMissingParameter {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(err.Error()), JSON: jsonerror.BadJSON(err.Error()),
} }
} else if err == threepid.ErrNotTrusted { } else if err == threepid.ErrNotTrusted {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.NotTrusted(body.IDServer), JSON: jsonerror.NotTrusted(body.IDServer),
} }
} else if err == common.ErrRoomNoExists { } else if err == common.ErrRoomNoExists {
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: http.StatusNotFound,
JSON: jsonerror.NotFound(err.Error()), JSON: jsonerror.NotFound(err.Error()),
} }
} else if err != nil { } else if err != nil {
@ -75,7 +75,7 @@ func SendMembership(
// emit a m.room.member one. // emit a m.room.member one.
if inviteStored { if inviteStored {
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
} }
} }
@ -85,12 +85,12 @@ func SendMembership(
) )
if err == errMissingUserID { if err == errMissingUserID {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(err.Error()), JSON: jsonerror.BadJSON(err.Error()),
} }
} else if err == common.ErrRoomNoExists { } else if err == common.ErrRoomNoExists {
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: http.StatusNotFound,
JSON: jsonerror.NotFound(err.Error()), JSON: jsonerror.NotFound(err.Error()),
} }
} else if err != nil { } else if err != nil {
@ -104,7 +104,7 @@ func SendMembership(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
} }
} }

View File

@ -48,13 +48,13 @@ func GetMemberships(
if !queryRes.HasBeenInRoom { if !queryRes.HasBeenInRoom {
return util.JSONResponse{ 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."), JSON: jsonerror.Forbidden("You aren't a member of the room and weren't previously a member of the room."),
} }
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: response{queryRes.JoinEvents}, JSON: response{queryRes.JoinEvents},
} }
} }

View File

@ -35,9 +35,9 @@ import (
func GetProfile( func GetProfile(
req *http.Request, accountDB *accounts.Database, userID string, req *http.Request, accountDB *accounts.Database, userID string,
) util.JSONResponse { ) util.JSONResponse {
if req.Method != "GET" { if req.Method != http.MethodGet {
return util.JSONResponse{ return util.JSONResponse{
Code: 405, Code: http.StatusMethodNotAllowed,
JSON: jsonerror.NotFound("Bad method"), JSON: jsonerror.NotFound("Bad method"),
} }
} }
@ -55,7 +55,7 @@ func GetProfile(
DisplayName: profile.DisplayName, DisplayName: profile.DisplayName,
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: res, JSON: res,
} }
} }
@ -77,7 +77,7 @@ func GetAvatarURL(
AvatarURL: profile.AvatarURL, AvatarURL: profile.AvatarURL,
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: res, JSON: res,
} }
} }
@ -90,7 +90,7 @@ func SetAvatarURL(
) util.JSONResponse { ) util.JSONResponse {
if userID != device.UserID { if userID != device.UserID {
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("userID does not match the current user"), JSON: jsonerror.Forbidden("userID does not match the current user"),
} }
} }
@ -103,7 +103,7 @@ func SetAvatarURL(
} }
if r.AvatarURL == "" { if r.AvatarURL == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("'avatar_url' must be supplied."), JSON: jsonerror.BadJSON("'avatar_url' must be supplied."),
} }
} }
@ -147,7 +147,7 @@ func SetAvatarURL(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
} }
} }
@ -169,7 +169,7 @@ func GetDisplayName(
DisplayName: profile.DisplayName, DisplayName: profile.DisplayName,
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: res, JSON: res,
} }
} }
@ -182,7 +182,7 @@ func SetDisplayName(
) util.JSONResponse { ) util.JSONResponse {
if userID != device.UserID { if userID != device.UserID {
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("userID does not match the current user"), JSON: jsonerror.Forbidden("userID does not match the current user"),
} }
} }
@ -195,7 +195,7 @@ func SetDisplayName(
} }
if r.DisplayName == "" { if r.DisplayName == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("'displayname' must be supplied."), JSON: jsonerror.BadJSON("'displayname' must be supplied."),
} }
} }
@ -239,7 +239,7 @@ func SetDisplayName(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
} }
} }

View File

@ -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 // https://github.com/matrix-org/synapse/blob/v0.20.0/synapse/rest/client/v2_alpha/register.py#L161
if len(username) > maxUsernameLength { if len(username) > maxUsernameLength {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(fmt.Sprintf("'username' >%d characters", maxUsernameLength)), JSON: jsonerror.BadJSON(fmt.Sprintf("'username' >%d characters", maxUsernameLength)),
} }
} else if !validUsernameRegex.MatchString(username) { } else if !validUsernameRegex.MatchString(username) {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidUsername("User ID can only contain characters a-z, 0-9, or '_-./'"), 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 } else if username[0] == '_' { // Regex checks its not a zero length string
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidUsername("User ID can't start with a '_'"), 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 // https://github.com/matrix-org/synapse/blob/v0.20.0/synapse/rest/client/v2_alpha/register.py#L161
if len(password) > maxPasswordLength { if len(password) > maxPasswordLength {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(fmt.Sprintf("'password' >%d characters", maxPasswordLength)), JSON: jsonerror.BadJSON(fmt.Sprintf("'password' >%d characters", maxPasswordLength)),
} }
} else if len(password) > 0 && len(password) < minPasswordLength { } else if len(password) > 0 && len(password) < minPasswordLength {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.WeakPassword(fmt.Sprintf("password too weak: min %d chars", minPasswordLength)), JSON: jsonerror.WeakPassword(fmt.Sprintf("password too weak: min %d chars", minPasswordLength)),
} }
} }
@ -179,14 +179,14 @@ func validateRecaptcha(
) *util.JSONResponse { ) *util.JSONResponse {
if !cfg.Matrix.RecaptchaEnabled { if !cfg.Matrix.RecaptchaEnabled {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Captcha registration is disabled"), JSON: jsonerror.BadJSON("Captcha registration is disabled"),
} }
} }
if response == "" { if response == "" {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Captcha response is required"), JSON: jsonerror.BadJSON("Captcha response is required"),
} }
} }
@ -202,7 +202,7 @@ func validateRecaptcha(
if err != nil { if err != nil {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 500, Code: http.StatusInternalServerError,
JSON: jsonerror.BadJSON("Error in requesting validation of captcha response"), JSON: jsonerror.BadJSON("Error in requesting validation of captcha response"),
} }
} }
@ -215,14 +215,14 @@ func validateRecaptcha(
body, err := ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 500, Code: http.StatusInternalServerError,
JSON: jsonerror.BadJSON("Error in contacting captcha server" + err.Error()), JSON: jsonerror.BadJSON("Error in contacting captcha server" + err.Error()),
} }
} }
err = json.Unmarshal(body, &r) err = json.Unmarshal(body, &r)
if err != nil { if err != nil {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 500, Code: http.StatusInternalServerError,
JSON: jsonerror.BadJSON("Error in unmarshaling captcha server's response: " + err.Error()), JSON: jsonerror.BadJSON("Error in unmarshaling captcha server's response: " + err.Error()),
} }
} }
@ -230,7 +230,7 @@ func validateRecaptcha(
// Check that we received a "success" // Check that we received a "success"
if !r.Success { if !r.Success {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 401, Code: http.StatusUnauthorized,
JSON: jsonerror.BadJSON("Invalid captcha response. Please try again."), JSON: jsonerror.BadJSON("Invalid captcha response. Please try again."),
} }
} }
@ -311,7 +311,7 @@ func validateApplicationService(
} }
if matchedApplicationService == nil { if matchedApplicationService == nil {
return "", &util.JSONResponse{ return "", &util.JSONResponse{
Code: 401, Code: http.StatusUnauthorized,
JSON: jsonerror.UnknownToken("Supplied access_token does not match any known application service"), 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 !UsernameIsWithinApplicationServiceNamespace(cfg, username, matchedApplicationService) {
// If we didn't find any matches, return M_EXCLUSIVE // If we didn't find any matches, return M_EXCLUSIVE
return "", &util.JSONResponse{ return "", &util.JSONResponse{
Code: 401, Code: http.StatusUnauthorized,
JSON: jsonerror.ASExclusive(fmt.Sprintf( JSON: jsonerror.ASExclusive(fmt.Sprintf(
"Supplied username %s did not match any namespaces for application service ID: %s", username, matchedApplicationService.ID)), "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 // Check this user does not fit multiple application service namespaces
if UsernameMatchesMultipleExclusiveNamespaces(cfg, username) { if UsernameMatchesMultipleExclusiveNamespaces(cfg, username) {
return "", &util.JSONResponse{ return "", &util.JSONResponse{
Code: 401, Code: http.StatusUnauthorized,
JSON: jsonerror.ASExclusive(fmt.Sprintf( JSON: jsonerror.ASExclusive(fmt.Sprintf(
"Supplied username %s matches multiple exclusive application service namespaces. Only 1 match allowed", username)), "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 no auth type is specified by the client, send back the list of available flows
if r.Auth.Type == "" { if r.Auth.Type == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: 401, Code: http.StatusUnauthorized,
JSON: newUserInteractiveResponse(sessionID, JSON: newUserInteractiveResponse(sessionID,
cfg.Derived.Registration.Flows, cfg.Derived.Registration.Params), cfg.Derived.Registration.Flows, cfg.Derived.Registration.Params),
} }
@ -386,7 +386,7 @@ func Register(
len(cfg.Derived.ApplicationServices) != 0 && len(cfg.Derived.ApplicationServices) != 0 &&
cfg.Derived.ExclusiveApplicationServicesUsernameRegexp.MatchString(r.Username) { cfg.Derived.ExclusiveApplicationServicesUsernameRegexp.MatchString(r.Username) {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.ASExclusive("This username is reserved by an application service."), JSON: jsonerror.ASExclusive("This username is reserved by an application service."),
} }
} }
@ -421,7 +421,7 @@ func handleRegistrationFlow(
// TODO: email / msisdn auth types. // TODO: email / msisdn auth types.
if cfg.Matrix.RegistrationDisabled && r.Auth.Type != authtypes.LoginTypeSharedSecret { 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 { switch r.Auth.Type {
@ -442,7 +442,7 @@ func handleRegistrationFlow(
if err != nil { if err != nil {
return httputil.LogThenError(req, err) return httputil.LogThenError(req, err)
} else if !valid { } 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 // Add SharedSecret to the list of completed registration stages
@ -470,7 +470,7 @@ func handleRegistrationFlow(
default: default:
return util.JSONResponse{ return util.JSONResponse{
Code: 501, Code: http.StatusNotImplemented,
JSON: jsonerror.Unknown("unknown/unimplemented auth type"), JSON: jsonerror.Unknown("unknown/unimplemented auth type"),
} }
} }
@ -502,7 +502,7 @@ func checkAndCompleteFlow(
// There are still more stages to complete. // There are still more stages to complete.
// Return the flows and those that have been completed. // Return the flows and those that have been completed.
return util.JSONResponse{ return util.JSONResponse{
Code: 401, Code: http.StatusUnauthorized,
JSON: newUserInteractiveResponse(sessionID, JSON: newUserInteractiveResponse(sessionID,
cfg.Derived.Registration.Flows, cfg.Derived.Registration.Params), cfg.Derived.Registration.Flows, cfg.Derived.Registration.Params),
} }
@ -528,13 +528,13 @@ func LegacyRegister(
}).Info("Processing registration request") }).Info("Processing registration request")
if cfg.Matrix.RegistrationDisabled && r.Type != authtypes.LoginTypeSharedSecret { 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 { switch r.Type {
case authtypes.LoginTypeSharedSecret: case authtypes.LoginTypeSharedSecret:
if cfg.Matrix.RegistrationSharedSecret == "" { 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) valid, err := isValidMacLogin(cfg, r.Username, r.Password, r.Admin, r.Mac)
@ -543,7 +543,7 @@ func LegacyRegister(
} }
if !valid { 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) 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) return completeRegistration(req.Context(), accountDB, deviceDB, r.Username, r.Password, "", nil)
default: default:
return util.JSONResponse{ return util.JSONResponse{
Code: 501, Code: http.StatusNotImplemented,
JSON: jsonerror.Unknown("unknown/unimplemented auth type"), 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 // All registration requests must specify what auth they are using to perform this request
if r.Type == "" { if r.Type == "" {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("invalid type"), JSON: jsonerror.BadJSON("invalid type"),
} }
} }
@ -596,14 +596,14 @@ func completeRegistration(
) util.JSONResponse { ) util.JSONResponse {
if username == "" { if username == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("missing username"), JSON: jsonerror.BadJSON("missing username"),
} }
} }
// Blank passwords are only allowed by registered application services // Blank passwords are only allowed by registered application services
if password == "" && appserviceID == "" { if password == "" && appserviceID == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("missing password"), JSON: jsonerror.BadJSON("missing password"),
} }
} }
@ -611,12 +611,12 @@ func completeRegistration(
acc, err := accountDB.CreateAccount(ctx, username, password, appserviceID) acc, err := accountDB.CreateAccount(ctx, username, password, appserviceID)
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 500, Code: http.StatusInternalServerError,
JSON: jsonerror.Unknown("failed to create account: " + err.Error()), JSON: jsonerror.Unknown("failed to create account: " + err.Error()),
} }
} else if acc == nil { } else if acc == nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.UserInUse("Desired user ID is already taken."), JSON: jsonerror.UserInUse("Desired user ID is already taken."),
} }
} }
@ -624,7 +624,7 @@ func completeRegistration(
token, err := auth.GenerateAccessToken() token, err := auth.GenerateAccessToken()
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 500, Code: http.StatusInternalServerError,
JSON: jsonerror.Unknown("Failed to generate access token"), JSON: jsonerror.Unknown("Failed to generate access token"),
} }
} }
@ -633,13 +633,13 @@ func completeRegistration(
dev, err := deviceDB.CreateDevice(ctx, username, nil, token, displayName) dev, err := deviceDB.CreateDevice(ctx, username, nil, token, displayName)
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 500, Code: http.StatusInternalServerError,
JSON: jsonerror.Unknown("failed to create device: " + err.Error()), JSON: jsonerror.Unknown("failed to create device: " + err.Error()),
} }
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: registerResponse{ JSON: registerResponse{
UserID: dev.UserID, UserID: dev.UserID,
AccessToken: dev.AccessToken, AccessToken: dev.AccessToken,
@ -765,19 +765,19 @@ func RegisterAvailable(
availability, availabilityErr := accountDB.CheckAccountAvailability(req.Context(), username) availability, availabilityErr := accountDB.CheckAccountAvailability(req.Context(), username)
if availabilityErr != nil { if availabilityErr != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 500, Code: http.StatusInternalServerError,
JSON: jsonerror.Unknown("failed to check availability: " + availabilityErr.Error()), JSON: jsonerror.Unknown("failed to check availability: " + availabilityErr.Error()),
} }
} }
if !availability { if !availability {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidUsername("A different user ID has already been registered for this session"), JSON: jsonerror.InvalidUsername("A different user ID has already been registered for this session"),
} }
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: availableResponse{ JSON: availableResponse{
Available: true, Available: true,
}, },

View File

@ -53,7 +53,7 @@ func Setup(
apiMux.Handle("/_matrix/client/versions", apiMux.Handle("/_matrix/client/versions",
common.MakeExternalAPI("versions", func(req *http.Request) util.JSONResponse { common.MakeExternalAPI("versions", func(req *http.Request) util.JSONResponse {
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct { JSON: struct {
Versions []string `json:"versions"` Versions []string `json:"versions"`
}{[]string{ }{[]string{
@ -63,7 +63,7 @@ func Setup(
}}, }},
} }
}), }),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
r0mux := apiMux.PathPrefix(pathPrefixR0).Subrouter() r0mux := apiMux.PathPrefix(pathPrefixR0).Subrouter()
v1mux := apiMux.PathPrefix(pathPrefixV1).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 { common.MakeAuthAPI("createRoom", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
return CreateRoom(req, device, cfg, producer, accountDB, aliasAPI) return CreateRoom(req, device, cfg, producer, accountDB, aliasAPI)
}), }),
).Methods("POST", "OPTIONS") ).Methods(http.MethodPost, http.MethodOptions)
r0mux.Handle("/join/{roomIDOrAlias}", r0mux.Handle("/join/{roomIDOrAlias}",
common.MakeAuthAPI("join", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("join", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
@ -81,26 +81,26 @@ func Setup(
req, device, vars["roomIDOrAlias"], cfg, federation, producer, queryAPI, aliasAPI, keyRing, accountDB, 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)}", r0mux.Handle("/rooms/{roomID}/{membership:(?:join|kick|ban|unban|leave|invite)}",
common.MakeAuthAPI("membership", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("membership", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
return SendMembership(req, accountDB, device, vars["roomID"], vars["membership"], cfg, queryAPI, producer) 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}", r0mux.Handle("/rooms/{roomID}/send/{eventType}",
common.MakeAuthAPI("send_message", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("send_message", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
return SendEvent(req, device, vars["roomID"], vars["eventType"], nil, nil, cfg, queryAPI, producer) 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}", r0mux.Handle("/rooms/{roomID}/send/{eventType}/{txnID}",
common.MakeAuthAPI("send_message", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("send_message", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
txnID := vars["txnID"] txnID := vars["txnID"]
return SendEvent(req, device, vars["roomID"], vars["eventType"], &txnID, nil, cfg, queryAPI, producer) 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:[^/]+/?}", r0mux.Handle("/rooms/{roomID}/state/{eventType:[^/]+/?}",
common.MakeAuthAPI("send_message", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("send_message", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
@ -112,59 +112,59 @@ func Setup(
} }
return SendEvent(req, device, vars["roomID"], eventType, nil, &emptyString, cfg, queryAPI, producer) 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}", r0mux.Handle("/rooms/{roomID}/state/{eventType}/{stateKey}",
common.MakeAuthAPI("send_message", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("send_message", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
stateKey := vars["stateKey"] stateKey := vars["stateKey"]
return SendEvent(req, device, vars["roomID"], vars["eventType"], nil, &stateKey, cfg, queryAPI, producer) 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 { r0mux.Handle("/register", common.MakeExternalAPI("register", func(req *http.Request) util.JSONResponse {
return Register(req, accountDB, deviceDB, &cfg) 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 { v1mux.Handle("/register", common.MakeExternalAPI("register", func(req *http.Request) util.JSONResponse {
return LegacyRegister(req, accountDB, deviceDB, &cfg) 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 { r0mux.Handle("/register/available", common.MakeExternalAPI("registerAvailable", func(req *http.Request) util.JSONResponse {
return RegisterAvailable(req, accountDB) return RegisterAvailable(req, accountDB)
})).Methods("GET", "OPTIONS") })).Methods(http.MethodGet, http.MethodOptions)
r0mux.Handle("/directory/room/{roomAlias}", r0mux.Handle("/directory/room/{roomAlias}",
common.MakeAuthAPI("directory_room", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("directory_room", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
return DirectoryRoom(req, vars["roomAlias"], federation, &cfg, aliasAPI) return DirectoryRoom(req, vars["roomAlias"], federation, &cfg, aliasAPI)
}), }),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
r0mux.Handle("/directory/room/{roomAlias}", r0mux.Handle("/directory/room/{roomAlias}",
common.MakeAuthAPI("directory_room", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("directory_room", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
return SetLocalAlias(req, device, vars["roomAlias"], &cfg, aliasAPI) return SetLocalAlias(req, device, vars["roomAlias"], &cfg, aliasAPI)
}), }),
).Methods("PUT", "OPTIONS") ).Methods(http.MethodPut, http.MethodOptions)
r0mux.Handle("/directory/room/{roomAlias}", r0mux.Handle("/directory/room/{roomAlias}",
common.MakeAuthAPI("directory_room", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("directory_room", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
return RemoveLocalAlias(req, device, vars["roomAlias"], aliasAPI) return RemoveLocalAlias(req, device, vars["roomAlias"], aliasAPI)
}), }),
).Methods("DELETE", "OPTIONS") ).Methods(http.MethodDelete, http.MethodOptions)
r0mux.Handle("/logout", r0mux.Handle("/logout",
common.MakeAuthAPI("logout", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("logout", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
return Logout(req, deviceDB, device) return Logout(req, deviceDB, device)
}), }),
).Methods("POST", "OPTIONS") ).Methods(http.MethodPost, http.MethodOptions)
r0mux.Handle("/logout/all", r0mux.Handle("/logout/all",
common.MakeAuthAPI("logout", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("logout", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
return LogoutAll(req, deviceDB, device) return LogoutAll(req, deviceDB, device)
}), }),
).Methods("POST", "OPTIONS") ).Methods(http.MethodPost, http.MethodOptions)
// Stub endpoints required by Riot // Stub endpoints required by Riot
@ -172,7 +172,7 @@ func Setup(
common.MakeExternalAPI("login", func(req *http.Request) util.JSONResponse { common.MakeExternalAPI("login", func(req *http.Request) util.JSONResponse {
return Login(req, accountDB, deviceDB, cfg) return Login(req, accountDB, deviceDB, cfg)
}), }),
).Methods("GET", "POST", "OPTIONS") ).Methods(http.MethodGet, http.MethodPost, http.MethodOptions)
r0mux.Handle("/pushrules/", r0mux.Handle("/pushrules/",
common.MakeExternalAPI("push_rules", func(req *http.Request) util.JSONResponse { common.MakeExternalAPI("push_rules", func(req *http.Request) util.JSONResponse {
@ -187,25 +187,25 @@ func Setup(
} }
}`) }`)
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: &res, JSON: &res,
} }
}), }),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
r0mux.Handle("/user/{userId}/filter", r0mux.Handle("/user/{userId}/filter",
common.MakeAuthAPI("put_filter", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("put_filter", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
return PutFilter(req, device, accountDB, vars["userId"]) return PutFilter(req, device, accountDB, vars["userId"])
}), }),
).Methods("POST", "OPTIONS") ).Methods(http.MethodPost, http.MethodOptions)
r0mux.Handle("/user/{userId}/filter/{filterId}", r0mux.Handle("/user/{userId}/filter/{filterId}",
common.MakeAuthAPI("get_filter", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("get_filter", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
return GetFilter(req, device, accountDB, vars["userId"], vars["filterId"]) return GetFilter(req, device, accountDB, vars["userId"], vars["filterId"])
}), }),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
// Riot user settings // Riot user settings
@ -214,21 +214,21 @@ func Setup(
vars := mux.Vars(req) vars := mux.Vars(req)
return GetProfile(req, accountDB, vars["userID"]) return GetProfile(req, accountDB, vars["userID"])
}), }),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
r0mux.Handle("/profile/{userID}/avatar_url", r0mux.Handle("/profile/{userID}/avatar_url",
common.MakeExternalAPI("profile_avatar_url", func(req *http.Request) util.JSONResponse { common.MakeExternalAPI("profile_avatar_url", func(req *http.Request) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
return GetAvatarURL(req, accountDB, vars["userID"]) return GetAvatarURL(req, accountDB, vars["userID"])
}), }),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
r0mux.Handle("/profile/{userID}/avatar_url", r0mux.Handle("/profile/{userID}/avatar_url",
common.MakeAuthAPI("profile_avatar_url", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("profile_avatar_url", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
return SetAvatarURL(req, accountDB, device, vars["userID"], userUpdateProducer, &cfg, producer, queryAPI) 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 // Browsers use the OPTIONS HTTP method to check if the CORS policy allows
// PUT requests, so we need to allow this method // PUT requests, so we need to allow this method
@ -237,14 +237,14 @@ func Setup(
vars := mux.Vars(req) vars := mux.Vars(req)
return GetDisplayName(req, accountDB, vars["userID"]) return GetDisplayName(req, accountDB, vars["userID"])
}), }),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
r0mux.Handle("/profile/{userID}/displayname", r0mux.Handle("/profile/{userID}/displayname",
common.MakeAuthAPI("profile_displayname", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("profile_displayname", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
return SetDisplayName(req, accountDB, device, vars["userID"], userUpdateProducer, &cfg, producer, queryAPI) 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 // Browsers use the OPTIONS HTTP method to check if the CORS policy allows
// PUT requests, so we need to allow this method // 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 { common.MakeAuthAPI("account_3pid", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
return GetAssociated3PIDs(req, accountDB, device) return GetAssociated3PIDs(req, accountDB, device)
}), }),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
r0mux.Handle("/account/3pid", r0mux.Handle("/account/3pid",
common.MakeAuthAPI("account_3pid", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("account_3pid", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
return CheckAndSave3PIDAssociation(req, accountDB, device, cfg) return CheckAndSave3PIDAssociation(req, accountDB, device, cfg)
}), }),
).Methods("POST", "OPTIONS") ).Methods(http.MethodPost, http.MethodOptions)
unstableMux.Handle("/account/3pid/delete", unstableMux.Handle("/account/3pid/delete",
common.MakeAuthAPI("account_3pid", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("account_3pid", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
return Forget3PID(req, accountDB) return Forget3PID(req, accountDB)
}), }),
).Methods("POST", "OPTIONS") ).Methods(http.MethodPost, http.MethodOptions)
r0mux.Handle("/{path:(?:account/3pid|register)}/email/requestToken", r0mux.Handle("/{path:(?:account/3pid|register)}/email/requestToken",
common.MakeExternalAPI("account_3pid_request_token", func(req *http.Request) util.JSONResponse { common.MakeExternalAPI("account_3pid_request_token", func(req *http.Request) util.JSONResponse {
return RequestEmailToken(req, accountDB, cfg) return RequestEmailToken(req, accountDB, cfg)
}), }),
).Methods("POST", "OPTIONS") ).Methods(http.MethodPost, http.MethodOptions)
// Riot logs get flooded unless this is handled // Riot logs get flooded unless this is handled
r0mux.Handle("/presence/{userID}/status", r0mux.Handle("/presence/{userID}/status",
common.MakeExternalAPI("presence", func(req *http.Request) util.JSONResponse { common.MakeExternalAPI("presence", func(req *http.Request) util.JSONResponse {
// TODO: Set presence (probably the responsibility of a presence server not clientapi) // TODO: Set presence (probably the responsibility of a presence server not clientapi)
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
} }
}), }),
).Methods("PUT", "OPTIONS") ).Methods(http.MethodPut, http.MethodOptions)
r0mux.Handle("/voip/turnServer", r0mux.Handle("/voip/turnServer",
common.MakeAuthAPI("turn_server", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("turn_server", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
return RequestTurnServer(req, device, cfg) return RequestTurnServer(req, device, cfg)
}), }),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
unstableMux.Handle("/thirdparty/protocols", unstableMux.Handle("/thirdparty/protocols",
common.MakeExternalAPI("thirdparty_protocols", func(req *http.Request) util.JSONResponse { common.MakeExternalAPI("thirdparty_protocols", func(req *http.Request) util.JSONResponse {
// TODO: Return the third party protcols // TODO: Return the third party protcols
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
} }
}), }),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
r0mux.Handle("/rooms/{roomID}/initialSync", r0mux.Handle("/rooms/{roomID}/initialSync",
common.MakeExternalAPI("rooms_initial_sync", func(req *http.Request) util.JSONResponse { common.MakeExternalAPI("rooms_initial_sync", func(req *http.Request) util.JSONResponse {
// TODO: Allow people to peek into rooms. // TODO: Allow people to peek into rooms.
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: http.StatusForbidden,
JSON: jsonerror.GuestAccessForbidden("Guest access not implemented"), JSON: jsonerror.GuestAccessForbidden("Guest access not implemented"),
} }
}), }),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
r0mux.Handle("/user/{userID}/account_data/{type}", r0mux.Handle("/user/{userID}/account_data/{type}",
common.MakeAuthAPI("user_account_data", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("user_account_data", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
return SaveAccountData(req, accountDB, device, vars["userID"], "", vars["type"], syncProducer) 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}", r0mux.Handle("/user/{userID}/rooms/{roomID}/account_data/{type}",
common.MakeAuthAPI("user_account_data", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("user_account_data", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
return SaveAccountData(req, accountDB, device, vars["userID"], vars["roomID"], vars["type"], syncProducer) 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", r0mux.Handle("/rooms/{roomID}/members",
common.MakeAuthAPI("rooms_members", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("rooms_members", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
return GetMemberships(req, device, vars["roomID"], false, cfg, queryAPI) return GetMemberships(req, device, vars["roomID"], false, cfg, queryAPI)
}), }),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
r0mux.Handle("/rooms/{roomID}/joined_members", r0mux.Handle("/rooms/{roomID}/joined_members",
common.MakeAuthAPI("rooms_members", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("rooms_members", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
return GetMemberships(req, device, vars["roomID"], true, cfg, queryAPI) return GetMemberships(req, device, vars["roomID"], true, cfg, queryAPI)
}), }),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
r0mux.Handle("/rooms/{roomID}/read_markers", r0mux.Handle("/rooms/{roomID}/read_markers",
common.MakeExternalAPI("rooms_read_markers", func(req *http.Request) util.JSONResponse { common.MakeExternalAPI("rooms_read_markers", func(req *http.Request) util.JSONResponse {
// TODO: return the read_markers. // 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}", r0mux.Handle("/rooms/{roomID}/typing/{userID}",
common.MakeExternalAPI("rooms_typing", func(req *http.Request) util.JSONResponse { common.MakeExternalAPI("rooms_typing", func(req *http.Request) util.JSONResponse {
// TODO: handling typing // 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", r0mux.Handle("/devices",
common.MakeAuthAPI("get_devices", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("get_devices", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
return GetDevicesByLocalpart(req, deviceDB, device) return GetDevicesByLocalpart(req, deviceDB, device)
}), }),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
r0mux.Handle("/device/{deviceID}", r0mux.Handle("/device/{deviceID}",
common.MakeAuthAPI("get_device", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("get_device", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
return GetDeviceByID(req, deviceDB, device, vars["deviceID"]) return GetDeviceByID(req, deviceDB, device, vars["deviceID"])
}), }),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
r0mux.Handle("/devices/{deviceID}", r0mux.Handle("/devices/{deviceID}",
common.MakeAuthAPI("device_data", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("device_data", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
return UpdateDeviceByID(req, deviceDB, device, vars["deviceID"]) return UpdateDeviceByID(req, deviceDB, device, vars["deviceID"])
}), }),
).Methods("PUT", "OPTIONS") ).Methods(http.MethodPut, http.MethodOptions)
// Stub implementations for sytest // Stub implementations for sytest
r0mux.Handle("/events", r0mux.Handle("/events",
common.MakeExternalAPI("events", func(req *http.Request) util.JSONResponse { 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{}{}, "chunk": []interface{}{},
"start": "", "start": "",
"end": "", "end": "",
}} }}
}), }),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
r0mux.Handle("/initialSync", r0mux.Handle("/initialSync",
common.MakeExternalAPI("initial_sync", func(req *http.Request) util.JSONResponse { 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": "", "end": "",
}} }}
}), }),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
} }

View File

@ -70,7 +70,7 @@ func SendEvent(
e, err := common.BuildEvent(req.Context(), &builder, cfg, queryAPI, &queryRes) e, err := common.BuildEvent(req.Context(), &builder, cfg, queryAPI, &queryRes)
if err == common.ErrRoomNoExists { if err == common.ErrRoomNoExists {
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Room does not exist"), JSON: jsonerror.NotFound("Room does not exist"),
} }
} else if err != nil { } else if err != nil {
@ -85,7 +85,7 @@ func SendEvent(
provider := gomatrixserverlib.NewAuthEvents(stateEvents) provider := gomatrixserverlib.NewAuthEvents(stateEvents)
if err = gomatrixserverlib.Allowed(*e, &provider); err != nil { if err = gomatrixserverlib.Allowed(*e, &provider); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden(err.Error()), // TODO: Is this error string comprehensible to the client? JSON: jsonerror.Forbidden(err.Error()), // TODO: Is this error string comprehensible to the client?
} }
} }
@ -106,7 +106,7 @@ func SendEvent(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: sendEventResponse{e.EventID()}, JSON: sendEventResponse{e.EventID()},
} }
} }

View File

@ -56,7 +56,7 @@ func RequestEmailToken(req *http.Request, accountDB *accounts.Database, cfg conf
if len(localpart) > 0 { if len(localpart) > 0 {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.MatrixError{ JSON: jsonerror.MatrixError{
ErrCode: "M_THREEPID_IN_USE", ErrCode: "M_THREEPID_IN_USE",
Err: accounts.Err3PIDInUse.Error(), 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) resp.SID, err = threepid.CreateSession(req.Context(), body, cfg)
if err == threepid.ErrNotTrusted { if err == threepid.ErrNotTrusted {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.NotTrusted(body.IDServer), JSON: jsonerror.NotTrusted(body.IDServer),
} }
} else if err != nil { } else if err != nil {
@ -75,7 +75,7 @@ func RequestEmailToken(req *http.Request, accountDB *accounts.Database, cfg conf
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: resp, JSON: resp,
} }
} }
@ -94,7 +94,7 @@ func CheckAndSave3PIDAssociation(
verified, address, medium, err := threepid.CheckAssociation(req.Context(), body.Creds, cfg) verified, address, medium, err := threepid.CheckAssociation(req.Context(), body.Creds, cfg)
if err == threepid.ErrNotTrusted { if err == threepid.ErrNotTrusted {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.NotTrusted(body.Creds.IDServer), JSON: jsonerror.NotTrusted(body.Creds.IDServer),
} }
} else if err != nil { } else if err != nil {
@ -103,7 +103,7 @@ func CheckAndSave3PIDAssociation(
if !verified { if !verified {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.MatrixError{ JSON: jsonerror.MatrixError{
ErrCode: "M_THREEPID_AUTH_FAILED", ErrCode: "M_THREEPID_AUTH_FAILED",
Err: "Failed to auth 3pid", Err: "Failed to auth 3pid",
@ -116,7 +116,7 @@ func CheckAndSave3PIDAssociation(
err = threepid.PublishAssociation(body.Creds, device.UserID, cfg) err = threepid.PublishAssociation(body.Creds, device.UserID, cfg)
if err == threepid.ErrNotTrusted { if err == threepid.ErrNotTrusted {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.NotTrusted(body.Creds.IDServer), JSON: jsonerror.NotTrusted(body.Creds.IDServer),
} }
} else if err != nil { } else if err != nil {
@ -135,7 +135,7 @@ func CheckAndSave3PIDAssociation(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
} }
} }
@ -155,7 +155,7 @@ func GetAssociated3PIDs(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: threePIDsResponse{threepids}, JSON: threePIDsResponse{threepids},
} }
} }
@ -172,7 +172,7 @@ func Forget3PID(req *http.Request, accountDB *accounts.Database) util.JSONRespon
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
} }
} }

View File

@ -15,12 +15,11 @@
package routing package routing
import ( import (
"net/http"
"crypto/hmac" "crypto/hmac"
"crypto/sha1" "crypto/sha1"
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"net/http"
"time" "time"
"github.com/matrix-org/dendrite/clientapi/auth/authtypes" "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 // TODO Guest Support
if len(turnConfig.URIs) == 0 || turnConfig.UserLifetime == "" { if len(turnConfig.URIs) == 0 || turnConfig.UserLifetime == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
} }
} }
@ -67,13 +66,13 @@ func RequestTurnServer(req *http.Request, device *authtypes.Device, cfg config.D
resp.Password = turnConfig.Password resp.Password = turnConfig.Password
} else { } else {
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
} }
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: resp, JSON: resp,
} }
} }

View File

@ -178,7 +178,7 @@ func queryIDServer(
func queryIDServerLookup(ctx context.Context, body *MembershipRequest) (*idServerLookupResponse, error) { func queryIDServerLookup(ctx context.Context, body *MembershipRequest) (*idServerLookupResponse, error) {
address := url.QueryEscape(body.Address) address := url.QueryEscape(body.Address)
url := fmt.Sprintf("https://%s/_matrix/identity/api/v1/lookup?medium=%s&address=%s", body.IDServer, body.Medium, 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 { if err != nil {
return nil, err return nil, err
} }
@ -238,7 +238,7 @@ func queryIDServerStoreInvite(
// server's database. // server's database.
url := fmt.Sprintf("https://%s/_matrix/identity/api/v1/store-invite", body.IDServer) 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 { if err != nil {
return nil, err return nil, err
} }
@ -266,7 +266,7 @@ func queryIDServerStoreInvite(
// or if the key couldn't be decoded from base64. // or if the key couldn't be decoded from base64.
func queryIDServerPubKey(ctx context.Context, idServerName string, keyID string) ([]byte, error) { func queryIDServerPubKey(ctx context.Context, idServerName string, keyID string) ([]byte, error) {
url := fmt.Sprintf("https://%s/_matrix/identity/api/v1/pubkey/%s", idServerName, keyID) 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 { if err != nil {
return nil, err return nil, err
} }

View File

@ -67,7 +67,7 @@ func CreateSession(
data.Add("email", req.Email) data.Add("email", req.Email)
data.Add("send_attempt", strconv.Itoa(req.SendAttempt)) 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 { if err != nil {
return "", err 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) 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 { if err != nil {
return false, "", "", err 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("client_secret", creds.Secret)
data.Add("mxid", userID) 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 { if err != nil {
return err return err
} }

View File

@ -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-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization") 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 // 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 // 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 // is what a lot of other people do (including synapse) and the clients

View File

@ -16,6 +16,7 @@ package routing
import ( import (
"context" "context"
"net/http"
"time" "time"
"github.com/matrix-org/dendrite/common/config" "github.com/matrix-org/dendrite/common/config"
@ -48,7 +49,7 @@ func GetEvent(
} }
if !authResponse.AllowedToSeeEvent { 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 var eventsResponse api.QueryEventsByIDResponse
@ -62,8 +63,8 @@ func GetEvent(
} }
if len(eventsResponse.Events) == 0 { 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]}
} }

View File

@ -41,7 +41,7 @@ func Invite(
var event gomatrixserverlib.Event var event gomatrixserverlib.Event
if err := json.Unmarshal(request.Content(), &event); err != nil { if err := json.Unmarshal(request.Content(), &event); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.NotJSON("The request body could not be decoded into valid JSON. " + err.Error()), 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. // Check that the room ID is correct.
if event.RoomID() != roomID { if event.RoomID() != roomID {
return util.JSONResponse{ 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"), 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. // Check that the event ID is correct.
if event.EventID() != eventID { if event.EventID() != eventID {
return util.JSONResponse{ 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"), 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. // Check that the event is from the server sending the request.
if event.Origin() != request.Origin() { if event.Origin() != request.Origin() {
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("The invite must be sent by the server it originated on"), 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 { if verifyResults[0].Error != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("The invite must be signed by the server it originated on"), 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 // Return the signed event to the originating server, it should then tell
// the other servers in the room that we have been invited. // the other servers in the room that we have been invited.
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: gomatrixserverlib.RespInvite{Event: signedEvent}, JSON: gomatrixserverlib.RespInvite{Event: signedEvent},
} }
} }

View File

@ -41,13 +41,13 @@ func MakeJoin(
_, domain, err := gomatrixserverlib.SplitID('@', userID) _, domain, err := gomatrixserverlib.SplitID('@', userID)
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Invalid UserID"), JSON: jsonerror.BadJSON("Invalid UserID"),
} }
} }
if domain != request.Origin() { if domain != request.Origin() {
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("The join must be sent by the server of the user"), 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) event, err := common.BuildEvent(ctx, &builder, cfg, query, &queryRes)
if err == common.ErrRoomNoExists { if err == common.ErrRoomNoExists {
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Room does not exist"), JSON: jsonerror.NotFound("Room does not exist"),
} }
} else if err != nil { } else if err != nil {
@ -83,13 +83,13 @@ func MakeJoin(
provider := gomatrixserverlib.NewAuthEvents(stateEvents) provider := gomatrixserverlib.NewAuthEvents(stateEvents)
if err = gomatrixserverlib.Allowed(*event, &provider); err != nil { if err = gomatrixserverlib.Allowed(*event, &provider); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden(err.Error()), JSON: jsonerror.Forbidden(err.Error()),
} }
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: map[string]interface{}{"event": builder}, JSON: map[string]interface{}{"event": builder},
} }
} }
@ -108,7 +108,7 @@ func SendJoin(
var event gomatrixserverlib.Event var event gomatrixserverlib.Event
if err := json.Unmarshal(request.Content(), &event); err != nil { if err := json.Unmarshal(request.Content(), &event); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.NotJSON("The request body could not be decoded into valid JSON. " + err.Error()), 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. // Check that the room ID is correct.
if event.RoomID() != roomID { if event.RoomID() != roomID {
return util.JSONResponse{ 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"), 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. // Check that the event ID is correct.
if event.EventID() != eventID { if event.EventID() != eventID {
return util.JSONResponse{ 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"), 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. // Check that the event is from the server sending the request.
if event.Origin() != request.Origin() { if event.Origin() != request.Origin() {
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("The join must be sent by the server it originated on"), 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 { if verifyResults[0].Error != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("The join must be signed by the server it originated on"), JSON: jsonerror.Forbidden("The join must be signed by the server it originated on"),
} }
} }
@ -175,7 +175,7 @@ func SendJoin(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: map[string]interface{}{ JSON: map[string]interface{}{
"state": stateAndAuthChainRepsonse.StateEvents, "state": stateAndAuthChainRepsonse.StateEvents,
"auth_chain": stateAndAuthChainRepsonse.AuthChainEvents, "auth_chain": stateAndAuthChainRepsonse.AuthChainEvents,

View File

@ -16,6 +16,7 @@ package routing
import ( import (
"encoding/json" "encoding/json"
"net/http"
"time" "time"
"github.com/matrix-org/dendrite/common/config" "github.com/matrix-org/dendrite/common/config"
@ -31,7 +32,7 @@ func LocalKeys(cfg config.Dendrite) util.JSONResponse {
if err != nil { if err != nil {
return util.ErrorResponse(err) 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) { func localKeys(cfg config.Dendrite, validUntil time.Time) (*gomatrixserverlib.ServerKeys, error) {

View File

@ -37,7 +37,7 @@ func GetProfile(
// httpReq.FormValue will return an empty string if value is not found // httpReq.FormValue will return an empty string if value is not found
if userID == "" { if userID == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.MissingArgument("The request body did not contain required argument 'user_id'."), JSON: jsonerror.MissingArgument("The request body did not contain required argument 'user_id'."),
} }
} }
@ -57,7 +57,7 @@ func GetProfile(
} }
var res interface{} var res interface{}
code := 200 code := http.StatusOK
if field != "" { if field != "" {
switch field { switch field {
@ -70,7 +70,7 @@ func GetProfile(
AvatarURL: profile.AvatarURL, AvatarURL: profile.AvatarURL,
} }
default: 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'.") res = jsonerror.InvalidArgumentValue("The request body did not contain an allowed value of argument 'field'. Allowed values are either: 'avatar_url', 'displayname'.")
} }
} else { } else {

View File

@ -37,14 +37,14 @@ func RoomAliasToID(
roomAlias := httpReq.FormValue("alias") roomAlias := httpReq.FormValue("alias")
if roomAlias == "" { if roomAlias == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Must supply room alias parameter."), JSON: jsonerror.BadJSON("Must supply room alias parameter."),
} }
} }
_, domain, err := gomatrixserverlib.SplitID('#', roomAlias) _, domain, err := gomatrixserverlib.SplitID('#', roomAlias)
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Room alias must be in the form '#localpart:domain'"), JSON: jsonerror.BadJSON("Room alias must be in the form '#localpart:domain'"),
} }
} }
@ -67,7 +67,7 @@ func RoomAliasToID(
} else { } else {
// If the response doesn't contain a non-empty string, return an error // If the response doesn't contain a non-empty string, return an error
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: http.StatusNotFound,
JSON: jsonerror.NotFound(fmt.Sprintf("Room alias %s not found", roomAlias)), JSON: jsonerror.NotFound(fmt.Sprintf("Room alias %s not found", roomAlias)),
} }
} }
@ -76,9 +76,9 @@ func RoomAliasToID(
if err != nil { if err != nil {
switch x := err.(type) { switch x := err.(type) {
case gomatrix.HTTPError: case gomatrix.HTTPError:
if x.Code == 404 { if x.Code == http.StatusNotFound {
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Room alias not found"), JSON: jsonerror.NotFound("Room alias not found"),
} }
} }
@ -90,7 +90,7 @@ func RoomAliasToID(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: resp, JSON: resp,
} }
} }

View File

@ -55,8 +55,8 @@ func Setup(
// return that key. // return that key.
// Even if we had more than one server key, we would probably still ignore the // 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. // {keyID} argument and always return a response containing all of the keys.
v2keysmux.Handle("/server/{keyID}", localKeys).Methods("GET") v2keysmux.Handle("/server/{keyID}", localKeys).Methods(http.MethodGet)
v2keysmux.Handle("/server/", localKeys).Methods("GET") v2keysmux.Handle("/server/", localKeys).Methods(http.MethodGet)
v1fedmux.Handle("/send/{txnID}/", common.MakeFedAPI( v1fedmux.Handle("/send/{txnID}/", common.MakeFedAPI(
"federation_send", cfg.Matrix.ServerName, keys, "federation_send", cfg.Matrix.ServerName, keys,
@ -67,7 +67,7 @@ func Setup(
cfg, query, producer, keys, federation, cfg, query, producer, keys, federation,
) )
}, },
)).Methods("PUT", "OPTIONS") )).Methods(http.MethodPut, http.MethodOptions)
v1fedmux.Handle("/invite/{roomID}/{eventID}", common.MakeFedAPI( v1fedmux.Handle("/invite/{roomID}/{eventID}", common.MakeFedAPI(
"federation_invite", cfg.Matrix.ServerName, keys, "federation_invite", cfg.Matrix.ServerName, keys,
@ -78,13 +78,13 @@ func Setup(
cfg, producer, keys, cfg, producer, keys,
) )
}, },
)).Methods("PUT", "OPTIONS") )).Methods(http.MethodPut, http.MethodOptions)
v1fedmux.Handle("/3pid/onbind", common.MakeExternalAPI("3pid_onbind", v1fedmux.Handle("/3pid/onbind", common.MakeExternalAPI("3pid_onbind",
func(req *http.Request) util.JSONResponse { func(req *http.Request) util.JSONResponse {
return CreateInvitesFrom3PIDInvites(req, query, cfg, producer, federation, accountDB) 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( v1fedmux.Handle("/exchange_third_party_invite/{roomID}", common.MakeFedAPI(
"exchange_third_party_invite", cfg.Matrix.ServerName, keys, "exchange_third_party_invite", cfg.Matrix.ServerName, keys,
@ -94,7 +94,7 @@ func Setup(
httpReq, request, vars["roomID"], query, cfg, federation, producer, httpReq, request, vars["roomID"], query, cfg, federation, producer,
) )
}, },
)).Methods("PUT", "OPTIONS") )).Methods(http.MethodPut, http.MethodOptions)
v1fedmux.Handle("/event/{eventID}", common.MakeFedAPI( v1fedmux.Handle("/event/{eventID}", common.MakeFedAPI(
"federation_get_event", cfg.Matrix.ServerName, keys, "federation_get_event", cfg.Matrix.ServerName, keys,
@ -104,7 +104,7 @@ func Setup(
httpReq.Context(), request, cfg, query, time.Now(), keys, vars["eventID"], httpReq.Context(), request, cfg, query, time.Now(), keys, vars["eventID"],
) )
}, },
)).Methods("GET") )).Methods(http.MethodGet)
v1fedmux.Handle("/query/directory/", common.MakeFedAPI( v1fedmux.Handle("/query/directory/", common.MakeFedAPI(
"federation_query_room_alias", cfg.Matrix.ServerName, keys, "federation_query_room_alias", cfg.Matrix.ServerName, keys,
@ -113,7 +113,7 @@ func Setup(
httpReq, federation, cfg, aliasAPI, httpReq, federation, cfg, aliasAPI,
) )
}, },
)).Methods("GET") )).Methods(http.MethodGet)
v1fedmux.Handle("/query/profile", common.MakeFedAPI( v1fedmux.Handle("/query/profile", common.MakeFedAPI(
"federation_query_profile", cfg.Matrix.ServerName, keys, "federation_query_profile", cfg.Matrix.ServerName, keys,
@ -122,7 +122,7 @@ func Setup(
httpReq, accountDB, cfg, httpReq, accountDB, cfg,
) )
}, },
)).Methods("GET") )).Methods(http.MethodGet)
v1fedmux.Handle("/make_join/{roomID}/{userID}", common.MakeFedAPI( v1fedmux.Handle("/make_join/{roomID}/{userID}", common.MakeFedAPI(
"federation_make_join", cfg.Matrix.ServerName, keys, "federation_make_join", cfg.Matrix.ServerName, keys,
@ -134,7 +134,7 @@ func Setup(
httpReq.Context(), httpReq, request, cfg, query, roomID, userID, httpReq.Context(), httpReq, request, cfg, query, roomID, userID,
) )
}, },
)).Methods("GET") )).Methods(http.MethodGet)
v1fedmux.Handle("/send_join/{roomID}/{userID}", common.MakeFedAPI( v1fedmux.Handle("/send_join/{roomID}/{userID}", common.MakeFedAPI(
"federation_send_join", cfg.Matrix.ServerName, keys, "federation_send_join", cfg.Matrix.ServerName, keys,
@ -146,12 +146,12 @@ func Setup(
httpReq.Context(), httpReq, request, cfg, query, producer, keys, roomID, userID, httpReq.Context(), httpReq, request, cfg, query, producer, keys, roomID, userID,
) )
}, },
)).Methods("PUT") )).Methods(http.MethodPut)
v1fedmux.Handle("/version", common.MakeExternalAPI( v1fedmux.Handle("/version", common.MakeExternalAPI(
"federation_version", "federation_version",
func(httpReq *http.Request) util.JSONResponse { func(httpReq *http.Request) util.JSONResponse {
return Version() return Version()
}, },
)).Methods("GET") )).Methods(http.MethodGet)
} }

View File

@ -50,7 +50,7 @@ func Send(
} }
if err := json.Unmarshal(request.Content(), &t); err != nil { if err := json.Unmarshal(request.Content(), &t); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.NotJSON("The request body could not be decoded into valid JSON. " + err.Error()), JSON: jsonerror.NotJSON("The request body could not be decoded into valid JSON. " + err.Error()),
} }
} }
@ -65,7 +65,7 @@ func Send(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: resp, JSON: resp,
} }
} }

View File

@ -86,7 +86,7 @@ func CreateInvitesFrom3PIDInvites(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
} }
} }
@ -104,7 +104,7 @@ func ExchangeThirdPartyInvite(
var builder gomatrixserverlib.EventBuilder var builder gomatrixserverlib.EventBuilder
if err := json.Unmarshal(request.Content(), &builder); err != nil { if err := json.Unmarshal(request.Content(), &builder); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.NotJSON("The request body could not be decoded into valid JSON. " + err.Error()), 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. // Check that the room ID is correct.
if builder.RoomID != roomID { if builder.RoomID != roomID {
return util.JSONResponse{ 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"), 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) _, targetDomain, err := gomatrixserverlib.SplitID('@', *builder.StateKey)
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The event's state key isn't a Matrix user ID"), 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. // Check that the target user is from the requesting homeserver.
if targetDomain != request.Origin() { if targetDomain != request.Origin() {
return util.JSONResponse{ 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"), 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) event, err := buildMembershipEvent(httpReq.Context(), &builder, queryAPI, cfg)
if err == errNotInRoom { if err == errNotInRoom {
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Unknown room " + roomID), JSON: jsonerror.NotFound("Unknown room " + roomID),
} }
} else if err != nil { } else if err != nil {
@ -160,7 +160,7 @@ func ExchangeThirdPartyInvite(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
} }
} }

View File

@ -15,6 +15,8 @@
package routing package routing
import ( import (
"net/http"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -29,5 +31,5 @@ type server struct {
// Version returns the server version // Version returns the server version
func Version() util.JSONResponse { 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"}}}
} }

View File

@ -107,9 +107,9 @@ func Download(
} }
// request validation // request validation
if req.Method != "GET" { if req.Method != http.MethodGet {
dReq.jsonErrorResponse(w, util.JSONResponse{ dReq.jsonErrorResponse(w, util.JSONResponse{
Code: 405, Code: http.StatusMethodNotAllowed,
JSON: jsonerror.Unknown("request method must be GET"), JSON: jsonerror.Unknown("request method must be GET"),
}) })
return return
@ -132,7 +132,7 @@ func Download(
if metadata == nil { if metadata == nil {
dReq.jsonErrorResponse(w, util.JSONResponse{ dReq.jsonErrorResponse(w, util.JSONResponse{
Code: 404, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("File not found"), JSON: jsonerror.NotFound("File not found"),
}) })
return return
@ -146,7 +146,7 @@ func (r *downloadRequest) jsonErrorResponse(w http.ResponseWriter, res util.JSON
if err != nil { if err != nil {
r.Logger.WithError(err).Error("Failed to marshal JSONResponse") r.Logger.WithError(err).Error("Failed to marshal JSONResponse")
// this should never fail to be marshalled so drop err to the floor // 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) 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 { func (r *downloadRequest) Validate() *util.JSONResponse {
if !mediaIDRegex.MatchString(string(r.MediaMetadata.MediaID)) { if !mediaIDRegex.MatchString(string(r.MediaMetadata.MediaID)) {
return &util.JSONResponse{ 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)), 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 // or by a DNS SRV record lookup when creating a request for remote files
if r.MediaMetadata.Origin == "" { if r.MediaMetadata.Origin == "" {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 404, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("serverName must be a non-empty string"), 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.IsThumbnailRequest {
if r.ThumbnailSize.Width <= 0 || r.ThumbnailSize.Height <= 0 { if r.ThumbnailSize.Width <= 0 || r.ThumbnailSize.Height <= 0 {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown("width and height must be greater than 0"), 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 { if r.ThumbnailSize.ResizeMethod != types.Crop && r.ThumbnailSize.ResizeMethod != types.Scale {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown("method must be one of crop or scale"), 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) 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 != http.StatusOK {
if resp.StatusCode == 404 { if resp.StatusCode == http.StatusNotFound {
return nil, nil return nil, nil
} }
r.Logger.WithFields(log.Fields{ r.Logger.WithFields(log.Fields{

View File

@ -52,17 +52,17 @@ func Setup(
func(req *http.Request, _ *authtypes.Device) util.JSONResponse { func(req *http.Request, _ *authtypes.Device) util.JSONResponse {
return Upload(req, cfg, db, activeThumbnailGeneration) return Upload(req, cfg, db, activeThumbnailGeneration)
}, },
)).Methods("POST", "OPTIONS") )).Methods(http.MethodPost, http.MethodOptions)
activeRemoteRequests := &types.ActiveRemoteRequests{ activeRemoteRequests := &types.ActiveRemoteRequests{
MXCToResult: map[string]*types.RemoteRequestResult{}, MXCToResult: map[string]*types.RemoteRequestResult{},
} }
r0mux.Handle("/download/{serverName}/{mediaId}", r0mux.Handle("/download/{serverName}/{mediaId}",
makeDownloadAPI("download", cfg, db, client, activeRemoteRequests, activeThumbnailGeneration), makeDownloadAPI("download", cfg, db, client, activeRemoteRequests, activeThumbnailGeneration),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
r0mux.Handle("/thumbnail/{serverName}/{mediaId}", r0mux.Handle("/thumbnail/{serverName}/{mediaId}",
makeDownloadAPI("thumbnail", cfg, db, client, activeRemoteRequests, activeThumbnailGeneration), makeDownloadAPI("thumbnail", cfg, db, client, activeRemoteRequests, activeThumbnailGeneration),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
} }
func makeDownloadAPI( func makeDownloadAPI(

View File

@ -64,7 +64,7 @@ func Upload(req *http.Request, cfg *config.Dendrite, db *storage.Database, activ
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: uploadResponse{ JSON: uploadResponse{
ContentURI: fmt.Sprintf("mxc://%s/%s", cfg.Matrix.ServerName, r.MediaMetadata.MediaID), 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. // all the metadata about the media being uploaded.
// Returns either an uploadRequest or an error formatted as a util.JSONResponse // Returns either an uploadRequest or an error formatted as a util.JSONResponse
func parseAndValidateRequest(req *http.Request, cfg *config.Dendrite) (*uploadRequest, *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{ return nil, &util.JSONResponse{
Code: 405, Code: http.StatusMethodNotAllowed,
JSON: jsonerror.Unknown("HTTP request method must be POST."), JSON: jsonerror.Unknown("HTTP request method must be POST."),
} }
} }
@ -123,7 +123,7 @@ func (r *uploadRequest) doUpload(
}).Warn("Error while transferring file") }).Warn("Error while transferring file")
fileutils.RemoveDir(tmpDir, r.Logger) fileutils.RemoveDir(tmpDir, r.Logger)
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown("Failed to upload"), JSON: jsonerror.Unknown("Failed to upload"),
} }
} }
@ -155,7 +155,7 @@ func (r *uploadRequest) doUpload(
r.MediaMetadata = mediaMetadata r.MediaMetadata = mediaMetadata
fileutils.RemoveDir(tmpDir, r.Logger) fileutils.RemoveDir(tmpDir, r.Logger)
return &util.JSONResponse{ return &util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: uploadResponse{ JSON: uploadResponse{
ContentURI: fmt.Sprintf("mxc://%s/%s", cfg.Matrix.ServerName, r.MediaMetadata.MediaID), 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 { func (r *uploadRequest) Validate(maxFileSizeBytes config.FileSizeBytes) *util.JSONResponse {
if r.MediaMetadata.FileSizeBytes < 1 { if r.MediaMetadata.FileSizeBytes < 1 {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 411, Code: http.StatusLengthRequired,
JSON: jsonerror.Unknown("HTTP Content-Length request header must be greater than zero."), JSON: jsonerror.Unknown("HTTP Content-Length request header must be greater than zero."),
} }
} }
if maxFileSizeBytes > 0 && r.MediaMetadata.FileSizeBytes > types.FileSizeBytes(maxFileSizeBytes) { if maxFileSizeBytes > 0 && r.MediaMetadata.FileSizeBytes > types.FileSizeBytes(maxFileSizeBytes) {
return &util.JSONResponse{ 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)), 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? // TODO: Check if the Content-Type is a valid type?
if r.MediaMetadata.ContentType == "" { if r.MediaMetadata.ContentType == "" {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown("HTTP Content-Type request header must be set."), JSON: jsonerror.Unknown("HTTP Content-Type request header must be set."),
} }
} }
if strings.HasPrefix(string(r.MediaMetadata.UploadName), "~") { if strings.HasPrefix(string(r.MediaMetadata.UploadName), "~") {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown("File name must not begin with '~'."), 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 // https://github.com/matrix-org/synapse/blob/v0.19.2/synapse/types.py#L92
if _, _, err := gomatrixserverlib.SplitID('@', string(r.MediaMetadata.UserID)); err != nil { if _, _, err := gomatrixserverlib.SplitID('@', string(r.MediaMetadata.UserID)); err != nil {
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("user id must be in the form @localpart:domain"), JSON: jsonerror.BadJSON("user id must be in the form @localpart:domain"),
} }
} }
@ -230,7 +230,7 @@ func (r *uploadRequest) storeFileAndMetadata(
if err != nil { if err != nil {
r.Logger.WithError(err).Error("Failed to move file.") r.Logger.WithError(err).Error("Failed to move file.")
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown("Failed to upload"), JSON: jsonerror.Unknown("Failed to upload"),
} }
} }
@ -247,7 +247,7 @@ func (r *uploadRequest) storeFileAndMetadata(
fileutils.RemoveDir(types.Path(path.Dir(string(finalPath))), r.Logger) fileutils.RemoveDir(types.Path(path.Dir(string(finalPath))), r.Logger)
} }
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown("Failed to upload"), JSON: jsonerror.Unknown("Failed to upload"),
} }
} }

View File

@ -45,7 +45,7 @@ func GetVisibility(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: v, JSON: v,
} }
} }
@ -67,7 +67,7 @@ func SetVisibility(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
} }
} }

View File

@ -82,7 +82,7 @@ func GetPublicRooms(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: response, JSON: response,
} }
} }
@ -90,7 +90,7 @@ func GetPublicRooms(
// fillPublicRoomsReq fills the Limit, Since and Filter attributes of a GET or POST request // fillPublicRoomsReq fills the Limit, Since and Filter attributes of a GET or POST request
// on /publicRooms by parsing the incoming HTTP request // on /publicRooms by parsing the incoming HTTP request
func fillPublicRoomsReq(httpReq *http.Request, request *publicRoomReq) *util.JSONResponse { 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")) limit, err := strconv.Atoi(httpReq.FormValue("limit"))
// Atoi returns 0 and an error when trying to parse an empty string // 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 // 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.Limit = int16(limit)
request.Since = httpReq.FormValue("since") request.Since = httpReq.FormValue("since")
return nil return nil
} else if httpReq.Method == "POST" { } else if httpReq.Method == http.MethodPost {
return httputil.UnmarshalJSONRequest(httpReq, request) return httputil.UnmarshalJSONRequest(httpReq, request)
} }
return &util.JSONResponse{ return &util.JSONResponse{
Code: 405, Code: http.StatusMethodNotAllowed,
JSON: jsonerror.NotFound("Bad method"), JSON: jsonerror.NotFound("Bad method"),
} }
} }

View File

@ -36,16 +36,16 @@ func Setup(apiMux *mux.Router, deviceDB *devices.Database, publicRoomsDB *storag
vars := mux.Vars(req) vars := mux.Vars(req)
return directory.GetVisibility(req, publicRoomsDB, vars["roomID"]) return directory.GetVisibility(req, publicRoomsDB, vars["roomID"])
}), }),
).Methods("GET", "OPTIONS") ).Methods(http.MethodGet, http.MethodOptions)
r0mux.Handle("/directory/list/room/{roomID}", r0mux.Handle("/directory/list/room/{roomID}",
common.MakeAuthAPI("directory_list", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("directory_list", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
return directory.SetVisibility(req, publicRoomsDB, vars["roomID"]) return directory.SetVisibility(req, publicRoomsDB, vars["roomID"])
}), }),
).Methods("PUT", "OPTIONS") ).Methods(http.MethodPut, http.MethodOptions)
r0mux.Handle("/publicRooms", r0mux.Handle("/publicRooms",
common.MakeExternalAPI("public_rooms", func(req *http.Request) util.JSONResponse { common.MakeExternalAPI("public_rooms", func(req *http.Request) util.JSONResponse {
return directory.GetPublicRooms(req, publicRoomsDB) return directory.GetPublicRooms(req, publicRoomsDB)
}), }),
).Methods("GET", "POST", "OPTIONS") ).Methods(http.MethodGet, http.MethodPost, http.MethodOptions)
} }

View File

@ -225,7 +225,7 @@ func (r *RoomserverAliasAPI) SetupHTTP(servMux *http.ServeMux) {
if err := r.SetRoomAlias(req.Context(), &request, &response); err != nil { if err := r.SetRoomAlias(req.Context(), &request, &response); err != nil {
return util.ErrorResponse(err) return util.ErrorResponse(err)
} }
return util.JSONResponse{Code: 200, JSON: &response} return util.JSONResponse{Code: http.StatusOK, JSON: &response}
}), }),
) )
servMux.Handle( servMux.Handle(
@ -239,7 +239,7 @@ func (r *RoomserverAliasAPI) SetupHTTP(servMux *http.ServeMux) {
if err := r.GetAliasRoomID(req.Context(), &request, &response); err != nil { if err := r.GetAliasRoomID(req.Context(), &request, &response); err != nil {
return util.ErrorResponse(err) return util.ErrorResponse(err)
} }
return util.JSONResponse{Code: 200, JSON: &response} return util.JSONResponse{Code: http.StatusOK, JSON: &response}
}), }),
) )
servMux.Handle( servMux.Handle(
@ -253,7 +253,7 @@ func (r *RoomserverAliasAPI) SetupHTTP(servMux *http.ServeMux) {
if err := r.RemoveRoomAlias(req.Context(), &request, &response); err != nil { if err := r.RemoveRoomAlias(req.Context(), &request, &response); err != nil {
return util.ErrorResponse(err) return util.ErrorResponse(err)
} }
return util.JSONResponse{Code: 200, JSON: &response} return util.JSONResponse{Code: http.StatusOK, JSON: &response}
}), }),
) )
} }

View File

@ -21,10 +21,9 @@ import (
"fmt" "fmt"
"net/http" "net/http"
opentracing "github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext" "github.com/opentracing/opentracing-go/ext"
"github.com/opentracing/opentracing-go"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
) )
@ -371,7 +370,7 @@ func postJSON(
return err return err
} }
req, err := http.NewRequest("POST", apiURL, bytes.NewReader(jsonBytes)) req, err := http.NewRequest(http.MethodPost, apiURL, bytes.NewReader(jsonBytes))
if err != nil { if err != nil {
return err return err
} }
@ -394,7 +393,7 @@ func postJSON(
if err != nil { if err != nil {
return err return err
} }
if res.StatusCode != 200 { if res.StatusCode != http.StatusOK {
var errorBody struct { var errorBody struct {
Message string `json:"message"` Message string `json:"message"`
} }

View File

@ -84,12 +84,12 @@ func (r *RoomserverInputAPI) SetupHTTP(servMux *http.ServeMux) {
var request api.InputRoomEventsRequest var request api.InputRoomEventsRequest
var response api.InputRoomEventsResponse var response api.InputRoomEventsResponse
if err := json.NewDecoder(req.Body).Decode(&request); err != nil { 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 { if err := r.InputRoomEvents(req.Context(), &request, &response); err != nil {
return util.ErrorResponse(err) return util.ErrorResponse(err)
} }
return util.JSONResponse{Code: 200, JSON: &response} return util.JSONResponse{Code: http.StatusOK, JSON: &response}
}), }),
) )
} }

View File

@ -534,7 +534,7 @@ func (r *RoomserverQueryAPI) SetupHTTP(servMux *http.ServeMux) {
if err := r.QueryLatestEventsAndState(req.Context(), &request, &response); err != nil { if err := r.QueryLatestEventsAndState(req.Context(), &request, &response); err != nil {
return util.ErrorResponse(err) return util.ErrorResponse(err)
} }
return util.JSONResponse{Code: 200, JSON: &response} return util.JSONResponse{Code: http.StatusOK, JSON: &response}
}), }),
) )
servMux.Handle( servMux.Handle(
@ -548,7 +548,7 @@ func (r *RoomserverQueryAPI) SetupHTTP(servMux *http.ServeMux) {
if err := r.QueryStateAfterEvents(req.Context(), &request, &response); err != nil { if err := r.QueryStateAfterEvents(req.Context(), &request, &response); err != nil {
return util.ErrorResponse(err) return util.ErrorResponse(err)
} }
return util.JSONResponse{Code: 200, JSON: &response} return util.JSONResponse{Code: http.StatusOK, JSON: &response}
}), }),
) )
servMux.Handle( servMux.Handle(
@ -562,7 +562,7 @@ func (r *RoomserverQueryAPI) SetupHTTP(servMux *http.ServeMux) {
if err := r.QueryEventsByID(req.Context(), &request, &response); err != nil { if err := r.QueryEventsByID(req.Context(), &request, &response); err != nil {
return util.ErrorResponse(err) return util.ErrorResponse(err)
} }
return util.JSONResponse{Code: 200, JSON: &response} return util.JSONResponse{Code: http.StatusOK, JSON: &response}
}), }),
) )
servMux.Handle( servMux.Handle(
@ -576,7 +576,7 @@ func (r *RoomserverQueryAPI) SetupHTTP(servMux *http.ServeMux) {
if err := r.QueryMembershipsForRoom(req.Context(), &request, &response); err != nil { if err := r.QueryMembershipsForRoom(req.Context(), &request, &response); err != nil {
return util.ErrorResponse(err) return util.ErrorResponse(err)
} }
return util.JSONResponse{Code: 200, JSON: &response} return util.JSONResponse{Code: http.StatusOK, JSON: &response}
}), }),
) )
servMux.Handle( servMux.Handle(
@ -590,7 +590,7 @@ func (r *RoomserverQueryAPI) SetupHTTP(servMux *http.ServeMux) {
if err := r.QueryInvitesForUser(req.Context(), &request, &response); err != nil { if err := r.QueryInvitesForUser(req.Context(), &request, &response); err != nil {
return util.ErrorResponse(err) return util.ErrorResponse(err)
} }
return util.JSONResponse{Code: 200, JSON: &response} return util.JSONResponse{Code: http.StatusOK, JSON: &response}
}), }),
) )
servMux.Handle( servMux.Handle(
@ -604,7 +604,7 @@ func (r *RoomserverQueryAPI) SetupHTTP(servMux *http.ServeMux) {
if err := r.QueryServerAllowedToSeeEvent(req.Context(), &request, &response); err != nil { if err := r.QueryServerAllowedToSeeEvent(req.Context(), &request, &response); err != nil {
return util.ErrorResponse(err) return util.ErrorResponse(err)
} }
return util.JSONResponse{Code: 200, JSON: &response} return util.JSONResponse{Code: http.StatusOK, JSON: &response}
}), }),
) )
servMux.Handle( servMux.Handle(
@ -618,7 +618,7 @@ func (r *RoomserverQueryAPI) SetupHTTP(servMux *http.ServeMux) {
if err := r.QueryStateAndAuthChain(req.Context(), &request, &response); err != nil { if err := r.QueryStateAndAuthChain(req.Context(), &request, &response); err != nil {
return util.ErrorResponse(err) return util.ErrorResponse(err)
} }
return util.JSONResponse{Code: 200, JSON: &response} return util.JSONResponse{Code: http.StatusOK, JSON: &response}
}), }),
) )
} }

View File

@ -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 { r0mux.Handle("/sync", common.MakeAuthAPI("sync", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
return srp.OnIncomingSyncRequest(req, device) 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 { r0mux.Handle("/rooms/{roomID}/state", common.MakeAuthAPI("room_state", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
return OnIncomingStateRequest(req, syncDB, vars["roomID"]) 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 { r0mux.Handle("/rooms/{roomID}/state/{type}", common.MakeAuthAPI("room_state", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)
return OnIncomingStateTypeRequest(req, syncDB, vars["roomID"], vars["type"], "") 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 { 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) vars := mux.Vars(req)
return OnIncomingStateTypeRequest(req, syncDB, vars["roomID"], vars["type"], vars["stateKey"]) return OnIncomingStateTypeRequest(req, syncDB, vars["roomID"], vars["type"], vars["stateKey"])
})).Methods("GET", "OPTIONS") })).Methods(http.MethodGet, http.MethodOptions)
} }

View File

@ -75,7 +75,7 @@ func OnIncomingStateRequest(req *http.Request, db *storage.SyncServerDatabase, r
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: resp, JSON: resp,
} }
} }
@ -102,7 +102,7 @@ func OnIncomingStateTypeRequest(req *http.Request, db *storage.SyncServerDatabas
if event == nil { if event == nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("cannot find state"), JSON: jsonerror.NotFound("cannot find state"),
} }
} }
@ -112,7 +112,7 @@ func OnIncomingStateTypeRequest(req *http.Request, db *storage.SyncServerDatabas
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: stateEvent.Content, JSON: stateEvent.Content,
} }
} }

View File

@ -51,7 +51,7 @@ func (rp *RequestPool) OnIncomingSyncRequest(req *http.Request, device *authtype
syncReq, err := newSyncRequest(req, *device) syncReq, err := newSyncRequest(req, *device)
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown(err.Error()), JSON: jsonerror.Unknown(err.Error()),
} }
} }
@ -70,7 +70,7 @@ func (rp *RequestPool) OnIncomingSyncRequest(req *http.Request, device *authtype
return httputil.LogThenError(req, err) return httputil.LogThenError(req, err)
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: syncData, JSON: syncData,
} }
} }
@ -92,7 +92,7 @@ func (rp *RequestPool) OnIncomingSyncRequest(req *http.Request, device *authtype
// Or for timeout to expire // Or for timeout to expire
case <-timer.C: case <-timer.C:
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: types.NewResponse(currPos), JSON: types.NewResponse(currPos),
} }
// Or for the request to be cancelled // Or for the request to be cancelled
@ -111,7 +111,7 @@ func (rp *RequestPool) OnIncomingSyncRequest(req *http.Request, device *authtype
} }
if !syncData.IsEmpty() { if !syncData.IsEmpty() {
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: http.StatusOK,
JSON: syncData, JSON: syncData,
} }
} }