unnecessary httprouter
This commit is contained in:
1 parent
16d4c8b521
commit
40c3406dcb
20 files changed
+443
-2063
No files matched your search
@@ -9,6 +9,13 @@ import(
|
||||
"party.at/party/cmd/party/common"
|
||||
"party.at/party/internal/data"
|
||||
"party.at/party/internal/validator"
|
||||
|
||||
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type Api struct {
|
||||
@@ -81,3 +88,353 @@ func (api *Api) Authenticate(next http.Handler) http.Handler {
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
type envelope map[string]interface{}
|
||||
|
||||
type apiError struct {
|
||||
Code common.ErrorCode `json:"code,omitempty"`
|
||||
Message string `json:"message"`
|
||||
Details map[string]string `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
|
||||
// ── JSON helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
func (api *Api) writeJSON(w http.ResponseWriter, status int, data envelope, headers http.Header) error {
|
||||
js, err := json.MarshalIndent(data, "", "\t")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
js = append(js, '\n')
|
||||
for key, value := range headers {
|
||||
w.Header()[key] = value
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
w.Write(js)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (api *Api) readJSON(w http.ResponseWriter, r *http.Request, dst interface{}) error {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 1048576)
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
|
||||
err := dec.Decode(dst)
|
||||
if err != nil {
|
||||
var syntaxError *json.SyntaxError
|
||||
var unmarshalTypeError *json.UnmarshalTypeError
|
||||
var invalidUnmarshalError *json.InvalidUnmarshalError
|
||||
|
||||
switch {
|
||||
case errors.As(err, &syntaxError):
|
||||
return fmt.Errorf("body contains badly-formed JSON (at character %d)", syntaxError.Offset)
|
||||
case errors.Is(err, io.ErrUnexpectedEOF):
|
||||
return errors.New("body contains badly-formed JSON")
|
||||
case errors.As(err, &unmarshalTypeError):
|
||||
if unmarshalTypeError.Field != "" {
|
||||
return fmt.Errorf("body contains incorrect JSON type for field %q", unmarshalTypeError.Field)
|
||||
}
|
||||
return fmt.Errorf("body contains incorrect JSON type (at character %d)", unmarshalTypeError.Offset)
|
||||
case errors.Is(err, io.EOF):
|
||||
return errors.New("body must not be empty")
|
||||
case strings.HasPrefix(err.Error(), "json: unknown field "):
|
||||
fieldName := strings.TrimPrefix(err.Error(), "json: unknown field ")
|
||||
return fmt.Errorf("body contains unknown key %s", fieldName)
|
||||
case err.Error() == "http: request body too large":
|
||||
return fmt.Errorf("body must not be larger than 1048576 bytes")
|
||||
case errors.As(err, &invalidUnmarshalError):
|
||||
panic(err)
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
err = dec.Decode(&struct{}{})
|
||||
if err != io.EOF {
|
||||
return errors.New("body must only contain a single JSON value")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (api *Api) readIDParam(r *http.Request) (int64, error) {
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
return 0, errors.New("invalid id parameter")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (api *Api) readString(qs url.Values, key, defaultValue string) string {
|
||||
if s := qs.Get(key); s != "" {
|
||||
return s
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
func (api *Api) readInt(qs url.Values, key string, defaultValue int, v *validator.Validator) int {
|
||||
s := qs.Get(key)
|
||||
if s == "" {
|
||||
return defaultValue
|
||||
}
|
||||
i, err := strconv.Atoi(s)
|
||||
if err != nil {
|
||||
v.AddError(key, "must be an integer value")
|
||||
return defaultValue
|
||||
}
|
||||
return i
|
||||
}
|
||||
|
||||
// ── Error responses ──────────────────────────────────────────────────────────
|
||||
|
||||
func (api *Api) LogError(r *http.Request, err error) {
|
||||
api.App.Logger.PrintError(err, map[string]string{
|
||||
"request_method": r.Method,
|
||||
"request_url": r.URL.String(),
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) errorResponse(w http.ResponseWriter, r *http.Request, status int, ae apiError) {
|
||||
if err := common.WriteJSON(w, status, common.Envelope{"error": ae}, nil); err != nil {
|
||||
api.App.LogError(r, err)
|
||||
w.WriteHeader(500)
|
||||
}
|
||||
}
|
||||
|
||||
func (api *Api) ServerErrorResponse(w http.ResponseWriter, r *http.Request, err error) {
|
||||
api.App.LogError(r, err)
|
||||
api.errorResponse(w, r, http.StatusInternalServerError, apiError{
|
||||
Message: "the server encountered a problem and could not process your request",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) NotFoundResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusNotFound, apiError{
|
||||
Message: "the requested resource could not be found",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) MethodNotAllowedResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusMethodNotAllowed, apiError{
|
||||
Message: fmt.Sprintf("the %s method is not supported for this resource", r.Method),
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) BadRequestResponse(w http.ResponseWriter, r *http.Request, err error) {
|
||||
api.errorResponse(w, r, http.StatusBadRequest, apiError{Message: err.Error()})
|
||||
}
|
||||
|
||||
func (api *Api) FailedValidationResponse(w http.ResponseWriter, r *http.Request, errors map[string]string) {
|
||||
api.errorResponse(w, r, http.StatusUnprocessableEntity, apiError{
|
||||
Code: common.ErrCodeValidationFailed,
|
||||
Message: "validation failed",
|
||||
Details: errors,
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) EditConflictResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusConflict, apiError{
|
||||
Code: common.ErrCodeEditConflict,
|
||||
Message: "unable to update the record due to an edit conflict, please try again",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) InvalidCredentialsResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusUnauthorized, apiError{
|
||||
Code: common.ErrCodeInvalidCredentials,
|
||||
Message: "invalid authentication credentials",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) InvalidAuthenticationTokenResponse(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("WWW-Authenticate", "Bearer")
|
||||
api.errorResponse(w, r, http.StatusUnauthorized, apiError{
|
||||
Code: common.ErrCodeInvalidAuthToken,
|
||||
Message: "invalid or missing authentication token",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) RateLimitExceededResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusTooManyRequests, apiError{
|
||||
Message: "rate limit exceeded",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) AuthenticationRequiredResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusUnauthorized, apiError{
|
||||
Code: common.ErrCodeAuthRequired,
|
||||
Message: "you must be authenticated to access this resource",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) InactiveAccountResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusForbidden, apiError{
|
||||
Code: common.ErrCodeInactiveAccount,
|
||||
Message: "your user account must be activated to access this resource",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) NotPermittedResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusForbidden, apiError{
|
||||
Code: common.ErrCodeNotPermitted,
|
||||
Message: "your user account doesn't have the necessary permissions to access this resource",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) AlreadyVotedResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusConflict, apiError{
|
||||
Code: common.ErrCodeAlreadyVoted,
|
||||
Message: "your user account already voted for this issue",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) AlreadyBlindSignedResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusConflict, apiError{
|
||||
Code: common.ErrCodeAlreadyBlindSigned,
|
||||
Message: "already requested a blind signature for this issue",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) BlindedVoteOutOfRangeResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusUnprocessableEntity, apiError{
|
||||
Code: common.ErrCodeBlindedVoteRange,
|
||||
Message: "blinded_vote is out of valid range",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) InvalidSignatureResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusUnprocessableEntity, apiError{
|
||||
Code: common.ErrCodeInvalidSignature,
|
||||
Message: "invalid signature",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) VoteAlreadyCastResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusConflict, apiError{
|
||||
Code: common.ErrCodeVoteAlreadyCast,
|
||||
Message: "this vote has already been cast",
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// func (app *Application) errorResponse(w http.ResponseWriter, r *http.Request, status int, ae apiError) {
|
||||
// if err := WriteJSON(w, status, Envelope{"error": ae}, nil); err != nil {
|
||||
// app.LogError(r, err)
|
||||
// w.WriteHeader(500)
|
||||
// }
|
||||
// }
|
||||
|
||||
// func (app *Application) ServerErrorResponse(w http.ResponseWriter, r *http.Request, err error) {
|
||||
// app.LogError(r, err)
|
||||
// app.errorResponse(w, r, http.StatusInternalServerError, apiError{
|
||||
// Message: "the server encountered a problem and could not process your request",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) NotFoundResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusNotFound, apiError{
|
||||
// Message: "the requested resource could not be found",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) MethodNotAllowedResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusMethodNotAllowed, apiError{
|
||||
// Message: fmt.Sprintf("the %s method is not supported for this resource", r.Method),
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) BadRequestResponse(w http.ResponseWriter, r *http.Request, err error) {
|
||||
// app.errorResponse(w, r, http.StatusBadRequest, apiError{Message: err.Error()})
|
||||
// }
|
||||
|
||||
// func (app *Application) FailedValidationResponse(w http.ResponseWriter, r *http.Request, errors map[string]string) {
|
||||
// app.errorResponse(w, r, http.StatusUnprocessableEntity, apiError{
|
||||
// Code: ErrCodeValidationFailed,
|
||||
// Message: "validation failed",
|
||||
// Details: errors,
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) EditConflictResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusConflict, apiError{
|
||||
// Code: ErrCodeEditConflict,
|
||||
// Message: "unable to update the record due to an edit conflict, please try again",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) InvalidCredentialsResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusUnauthorized, apiError{
|
||||
// Code: ErrCodeInvalidCredentials,
|
||||
// Message: "invalid authentication credentials",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) RateLimitExceededResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusTooManyRequests, apiError{
|
||||
// Message: "rate limit exceeded",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) AuthenticationRequiredResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusUnauthorized, apiError{
|
||||
// Code: ErrCodeAuthRequired,
|
||||
// Message: "you must be authenticated to access this resource",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) InactiveAccountResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusForbidden, apiError{
|
||||
// Code: ErrCodeInactiveAccount,
|
||||
// Message: "your user account must be activated to access this resource",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) NotPermittedResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusForbidden, apiError{
|
||||
// Code: ErrCodeNotPermitted,
|
||||
// Message: "your user account doesn't have the necessary permissions to access this resource",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) AlreadyVotedResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusConflict, apiError{
|
||||
// Code: ErrCodeAlreadyVoted,
|
||||
// Message: "your user account already voted for this issue",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) AlreadyBlindSignedResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusConflict, apiError{
|
||||
// Code: ErrCodeAlreadyBlindSigned,
|
||||
// Message: "already requested a blind signature for this issue",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) BlindedVoteOutOfRangeResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusUnprocessableEntity, apiError{
|
||||
// Code: ErrCodeBlindedVoteRange,
|
||||
// Message: "blinded_vote is out of valid range",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) InvalidSignatureResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusUnprocessableEntity, apiError{
|
||||
// Code: ErrCodeInvalidSignature,
|
||||
// Message: "invalid signature",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) VoteAlreadyCastResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusConflict, apiError{
|
||||
// Code: ErrCodeVoteAlreadyCast,
|
||||
// Message: "this vote has already been cast",
|
||||
// })
|
||||
// }
|
||||
|
||||
@@ -1,366 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"party.at/party/cmd/party/common"
|
||||
"party.at/party/internal/validator"
|
||||
)
|
||||
|
||||
type envelope map[string]interface{}
|
||||
|
||||
type apiError struct {
|
||||
Code common.ErrorCode `json:"code,omitempty"`
|
||||
Message string `json:"message"`
|
||||
Details map[string]string `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
|
||||
// ── JSON helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
func (api *Api) writeJSON(w http.ResponseWriter, status int, data envelope, headers http.Header) error {
|
||||
js, err := json.MarshalIndent(data, "", "\t")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
js = append(js, '\n')
|
||||
for key, value := range headers {
|
||||
w.Header()[key] = value
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
w.Write(js)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (api *Api) readJSON(w http.ResponseWriter, r *http.Request, dst interface{}) error {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 1048576)
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
|
||||
err := dec.Decode(dst)
|
||||
if err != nil {
|
||||
var syntaxError *json.SyntaxError
|
||||
var unmarshalTypeError *json.UnmarshalTypeError
|
||||
var invalidUnmarshalError *json.InvalidUnmarshalError
|
||||
|
||||
switch {
|
||||
case errors.As(err, &syntaxError):
|
||||
return fmt.Errorf("body contains badly-formed JSON (at character %d)", syntaxError.Offset)
|
||||
case errors.Is(err, io.ErrUnexpectedEOF):
|
||||
return errors.New("body contains badly-formed JSON")
|
||||
case errors.As(err, &unmarshalTypeError):
|
||||
if unmarshalTypeError.Field != "" {
|
||||
return fmt.Errorf("body contains incorrect JSON type for field %q", unmarshalTypeError.Field)
|
||||
}
|
||||
return fmt.Errorf("body contains incorrect JSON type (at character %d)", unmarshalTypeError.Offset)
|
||||
case errors.Is(err, io.EOF):
|
||||
return errors.New("body must not be empty")
|
||||
case strings.HasPrefix(err.Error(), "json: unknown field "):
|
||||
fieldName := strings.TrimPrefix(err.Error(), "json: unknown field ")
|
||||
return fmt.Errorf("body contains unknown key %s", fieldName)
|
||||
case err.Error() == "http: request body too large":
|
||||
return fmt.Errorf("body must not be larger than 1048576 bytes")
|
||||
case errors.As(err, &invalidUnmarshalError):
|
||||
panic(err)
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
err = dec.Decode(&struct{}{})
|
||||
if err != io.EOF {
|
||||
return errors.New("body must only contain a single JSON value")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (api *Api) readIDParam(r *http.Request) (int64, error) {
|
||||
params := httprouter.ParamsFromContext(r.Context())
|
||||
id, err := strconv.ParseInt(params.ByName("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
return 0, errors.New("invalid id parameter")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (api *Api) readString(qs url.Values, key, defaultValue string) string {
|
||||
if s := qs.Get(key); s != "" {
|
||||
return s
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
func (api *Api) readInt(qs url.Values, key string, defaultValue int, v *validator.Validator) int {
|
||||
s := qs.Get(key)
|
||||
if s == "" {
|
||||
return defaultValue
|
||||
}
|
||||
i, err := strconv.Atoi(s)
|
||||
if err != nil {
|
||||
v.AddError(key, "must be an integer value")
|
||||
return defaultValue
|
||||
}
|
||||
return i
|
||||
}
|
||||
|
||||
// ── Error responses ──────────────────────────────────────────────────────────
|
||||
|
||||
func (api *Api) LogError(r *http.Request, err error) {
|
||||
api.App.Logger.PrintError(err, map[string]string{
|
||||
"request_method": r.Method,
|
||||
"request_url": r.URL.String(),
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) errorResponse(w http.ResponseWriter, r *http.Request, status int, ae apiError) {
|
||||
if err := common.WriteJSON(w, status, common.Envelope{"error": ae}, nil); err != nil {
|
||||
api.App.LogError(r, err)
|
||||
w.WriteHeader(500)
|
||||
}
|
||||
}
|
||||
|
||||
func (api *Api) ServerErrorResponse(w http.ResponseWriter, r *http.Request, err error) {
|
||||
api.App.LogError(r, err)
|
||||
api.errorResponse(w, r, http.StatusInternalServerError, apiError{
|
||||
Message: "the server encountered a problem and could not process your request",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) NotFoundResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusNotFound, apiError{
|
||||
Message: "the requested resource could not be found",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) MethodNotAllowedResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusMethodNotAllowed, apiError{
|
||||
Message: fmt.Sprintf("the %s method is not supported for this resource", r.Method),
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) BadRequestResponse(w http.ResponseWriter, r *http.Request, err error) {
|
||||
api.errorResponse(w, r, http.StatusBadRequest, apiError{Message: err.Error()})
|
||||
}
|
||||
|
||||
func (api *Api) FailedValidationResponse(w http.ResponseWriter, r *http.Request, errors map[string]string) {
|
||||
api.errorResponse(w, r, http.StatusUnprocessableEntity, apiError{
|
||||
Code: common.ErrCodeValidationFailed,
|
||||
Message: "validation failed",
|
||||
Details: errors,
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) EditConflictResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusConflict, apiError{
|
||||
Code: common.ErrCodeEditConflict,
|
||||
Message: "unable to update the record due to an edit conflict, please try again",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) InvalidCredentialsResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusUnauthorized, apiError{
|
||||
Code: common.ErrCodeInvalidCredentials,
|
||||
Message: "invalid authentication credentials",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) InvalidAuthenticationTokenResponse(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("WWW-Authenticate", "Bearer")
|
||||
api.errorResponse(w, r, http.StatusUnauthorized, apiError{
|
||||
Code: common.ErrCodeInvalidAuthToken,
|
||||
Message: "invalid or missing authentication token",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) RateLimitExceededResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusTooManyRequests, apiError{
|
||||
Message: "rate limit exceeded",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) AuthenticationRequiredResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusUnauthorized, apiError{
|
||||
Code: common.ErrCodeAuthRequired,
|
||||
Message: "you must be authenticated to access this resource",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) InactiveAccountResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusForbidden, apiError{
|
||||
Code: common.ErrCodeInactiveAccount,
|
||||
Message: "your user account must be activated to access this resource",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) NotPermittedResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusForbidden, apiError{
|
||||
Code: common.ErrCodeNotPermitted,
|
||||
Message: "your user account doesn't have the necessary permissions to access this resource",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) AlreadyVotedResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusConflict, apiError{
|
||||
Code: common.ErrCodeAlreadyVoted,
|
||||
Message: "your user account already voted for this issue",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) AlreadyBlindSignedResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusConflict, apiError{
|
||||
Code: common.ErrCodeAlreadyBlindSigned,
|
||||
Message: "already requested a blind signature for this issue",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) BlindedVoteOutOfRangeResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusUnprocessableEntity, apiError{
|
||||
Code: common.ErrCodeBlindedVoteRange,
|
||||
Message: "blinded_vote is out of valid range",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) InvalidSignatureResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusUnprocessableEntity, apiError{
|
||||
Code: common.ErrCodeInvalidSignature,
|
||||
Message: "invalid signature",
|
||||
})
|
||||
}
|
||||
|
||||
func (api *Api) VoteAlreadyCastResponse(w http.ResponseWriter, r *http.Request) {
|
||||
api.errorResponse(w, r, http.StatusConflict, apiError{
|
||||
Code: common.ErrCodeVoteAlreadyCast,
|
||||
Message: "this vote has already been cast",
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// func (app *Application) errorResponse(w http.ResponseWriter, r *http.Request, status int, ae apiError) {
|
||||
// if err := WriteJSON(w, status, Envelope{"error": ae}, nil); err != nil {
|
||||
// app.LogError(r, err)
|
||||
// w.WriteHeader(500)
|
||||
// }
|
||||
// }
|
||||
|
||||
// func (app *Application) ServerErrorResponse(w http.ResponseWriter, r *http.Request, err error) {
|
||||
// app.LogError(r, err)
|
||||
// app.errorResponse(w, r, http.StatusInternalServerError, apiError{
|
||||
// Message: "the server encountered a problem and could not process your request",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) NotFoundResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusNotFound, apiError{
|
||||
// Message: "the requested resource could not be found",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) MethodNotAllowedResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusMethodNotAllowed, apiError{
|
||||
// Message: fmt.Sprintf("the %s method is not supported for this resource", r.Method),
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) BadRequestResponse(w http.ResponseWriter, r *http.Request, err error) {
|
||||
// app.errorResponse(w, r, http.StatusBadRequest, apiError{Message: err.Error()})
|
||||
// }
|
||||
|
||||
// func (app *Application) FailedValidationResponse(w http.ResponseWriter, r *http.Request, errors map[string]string) {
|
||||
// app.errorResponse(w, r, http.StatusUnprocessableEntity, apiError{
|
||||
// Code: ErrCodeValidationFailed,
|
||||
// Message: "validation failed",
|
||||
// Details: errors,
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) EditConflictResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusConflict, apiError{
|
||||
// Code: ErrCodeEditConflict,
|
||||
// Message: "unable to update the record due to an edit conflict, please try again",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) InvalidCredentialsResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusUnauthorized, apiError{
|
||||
// Code: ErrCodeInvalidCredentials,
|
||||
// Message: "invalid authentication credentials",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) RateLimitExceededResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusTooManyRequests, apiError{
|
||||
// Message: "rate limit exceeded",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) AuthenticationRequiredResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusUnauthorized, apiError{
|
||||
// Code: ErrCodeAuthRequired,
|
||||
// Message: "you must be authenticated to access this resource",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) InactiveAccountResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusForbidden, apiError{
|
||||
// Code: ErrCodeInactiveAccount,
|
||||
// Message: "your user account must be activated to access this resource",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) NotPermittedResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusForbidden, apiError{
|
||||
// Code: ErrCodeNotPermitted,
|
||||
// Message: "your user account doesn't have the necessary permissions to access this resource",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) AlreadyVotedResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusConflict, apiError{
|
||||
// Code: ErrCodeAlreadyVoted,
|
||||
// Message: "your user account already voted for this issue",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) AlreadyBlindSignedResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusConflict, apiError{
|
||||
// Code: ErrCodeAlreadyBlindSigned,
|
||||
// Message: "already requested a blind signature for this issue",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) BlindedVoteOutOfRangeResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusUnprocessableEntity, apiError{
|
||||
// Code: ErrCodeBlindedVoteRange,
|
||||
// Message: "blinded_vote is out of valid range",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) InvalidSignatureResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusUnprocessableEntity, apiError{
|
||||
// Code: ErrCodeInvalidSignature,
|
||||
// Message: "invalid signature",
|
||||
// })
|
||||
// }
|
||||
|
||||
// func (app *Application) VoteAlreadyCastResponse(w http.ResponseWriter, r *http.Request) {
|
||||
// app.errorResponse(w, r, http.StatusConflict, apiError{
|
||||
// Code: ErrCodeVoteAlreadyCast,
|
||||
// Message: "this vote has already been cast",
|
||||
// })
|
||||
// }
|
||||
@@ -4,13 +4,10 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
)
|
||||
|
||||
func (api *Api) GetParlVoteDetail(w http.ResponseWriter, r *http.Request) {
|
||||
ps := httprouter.ParamsFromContext(r.Context())
|
||||
routePath := ps.ByName("path") // e.g. "/XXVIII/I/14"
|
||||
routePath := r.PathValue("path")
|
||||
routePath = strings.TrimPrefix(routePath, "/")
|
||||
if routePath == "" {
|
||||
api.BadRequestResponse(w, r, errors.New("path is required"))
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"party.at/party/cmd/party/common"
|
||||
"party.at/party/internal/data"
|
||||
"party.at/party/internal/validator"
|
||||
@@ -98,7 +97,9 @@ func (api *Api) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (api *Api) ReadUser(w http.ResponseWriter, r *http.Request) {
|
||||
var id int64
|
||||
if param := httprouter.ParamsFromContext(r.Context()).ByName("id"); param == "me" {
|
||||
param := r.PathValue("id")
|
||||
|
||||
if param == "me" {
|
||||
id = GetUser(r).ID
|
||||
} else {
|
||||
var err error
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"party.at/party/internal/validator"
|
||||
)
|
||||
|
||||
@@ -67,8 +66,7 @@ func (app *Application) ReadJSON(w http.ResponseWriter, r *http.Request, dst int
|
||||
}
|
||||
|
||||
func ReadIDParam(r *http.Request) (int64, error) {
|
||||
params := httprouter.ParamsFromContext(r.Context())
|
||||
id, err := strconv.ParseInt(params.ByName("id"), 10, 64)
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
return 0, errors.New("invalid id parameter")
|
||||
}
|
||||
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"party.at/party/internal/validator"
|
||||
)
|
||||
|
||||
@@ -49,14 +48,14 @@ func readInt(qs url.Values, key string, defaultValue int, v *validator.Validator
|
||||
return i
|
||||
}
|
||||
|
||||
func readIDParam(r *http.Request) (int64, error) {
|
||||
params := httprouter.ParamsFromContext(r.Context())
|
||||
id, err := strconv.ParseInt(params.ByName("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
return 0, errors.New("invalid id parameter")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
// func readIDParam(r *http.Request) (int64, error) {
|
||||
// params := httprouter.ParamsFromContext(r.Context())
|
||||
// id, err := strconv.ParseInt(params.ByName("id"), 10, 64)
|
||||
// if err != nil || id < 1 {
|
||||
// return 0, errors.New("invalid id parameter")
|
||||
// }
|
||||
// return id, nil
|
||||
// }
|
||||
|
||||
func WriteJSON(w http.ResponseWriter, status int, data Envelope, headers http.Header) error {
|
||||
js, err := json.MarshalIndent(data, "", "\t")
|
||||
|
||||
@@ -1,15 +1,9 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
// "encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
// "github.com/julienschmidt/httprouter"
|
||||
// "strconv"
|
||||
// "errors"
|
||||
// "party.at/party/internal/data"
|
||||
// "party.at/party/internal/validator"
|
||||
)
|
||||
|
||||
func ws(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
|
||||
"party.at/party/cmd/party/common"
|
||||
)
|
||||
|
||||
@@ -16,10 +13,7 @@ func TestReadIDParam(t *testing.T) {
|
||||
const test_id int64 = 3
|
||||
|
||||
r := httptest.NewRequest(http.MethodGet, "/v1/issues/" + strconv.FormatInt(test_id, 10), nil)
|
||||
|
||||
params := httprouter.Params{{Key: "id", Value: "3"}}
|
||||
ctx := context.WithValue(r.Context(), httprouter.ParamsKey, params)
|
||||
r = r.WithContext(ctx)
|
||||
r.SetPathValue("id", "3")
|
||||
|
||||
id, err := common.ReadIDParam(r)
|
||||
if err != nil {
|
||||
|
||||
+70
-67
@@ -4,92 +4,95 @@ import (
|
||||
"expvar"
|
||||
"net/http"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"party.at/party/cmd/party/common"
|
||||
"party.at/party/cmd/party/api"
|
||||
"party.at/party/cmd/party/web"
|
||||
)
|
||||
|
||||
func routes(app *common.Application) http.Handler {
|
||||
// ── API router (Bearer token auth) ──────────────────────────────────────
|
||||
|
||||
api := api.Api{
|
||||
// ── API router ──────────────────────────────────────────────────────────
|
||||
api := api.Api{
|
||||
App: app,
|
||||
}
|
||||
apiMux := http.NewServeMux()
|
||||
|
||||
apiRouter := httprouter.New()
|
||||
apiRouter.NotFound = http.HandlerFunc(api.NotFoundResponse)
|
||||
apiRouter.MethodNotAllowed = http.HandlerFunc(api.MethodNotAllowedResponse)
|
||||
// Note: Standard library doesn't have a simple .NotFound property.
|
||||
// You handle that by wrapping the final mux in middleware or a custom handler.
|
||||
|
||||
apiRouter.HandlerFunc(http.MethodGet, "/v1/healthcheck", api.Healthcheck)
|
||||
apiMux.HandleFunc("GET /v1/healthcheck", api.Healthcheck)
|
||||
|
||||
apiRouter.HandlerFunc(http.MethodGet, "/v1/issues", api.RequirePermission("issues:read", api.ListIssues))
|
||||
apiRouter.HandlerFunc(http.MethodPost, "/v1/issues", api.RequirePermission("issues:write", api.CreateIssue))
|
||||
apiRouter.HandlerFunc(http.MethodGet, "/v1/issues/:id", api.RequirePermission("issues:read", api.ReadIssue))
|
||||
apiRouter.HandlerFunc(http.MethodPatch, "/v1/issues/:id", api.RequirePermission("issues:write", api.UpdateIssue))
|
||||
apiRouter.HandlerFunc(http.MethodDelete, "/v1/issues/:id", api.RequirePermission("issues:write", api.DeleteIssue))
|
||||
apiRouter.HandlerFunc(http.MethodGet, "/v1/issues/:id/pubkey", api.RequirePermission("issues:read", api.ReadIssuePubKey))
|
||||
apiRouter.HandlerFunc(http.MethodPost, "/v1/issues/:id/blind-sign", api.RequirePermission("issues:read", api.BlindSignIssueVote))
|
||||
apiRouter.HandlerFunc(http.MethodPost, "/v1/votes", api.Vote)
|
||||
apiRouter.HandlerFunc(http.MethodPost, "/v1/users", api.CreateUser)
|
||||
apiRouter.HandlerFunc(http.MethodGet, "/v1/users", api.RequirePermission("users:read", api.ListUsers))
|
||||
apiRouter.HandlerFunc(http.MethodGet, "/v1/users/:id", api.RequireAuthenticatedUser(api.ReadUser))
|
||||
apiRouter.HandlerFunc(http.MethodDelete, "/v1/users/:id", api.DeleteUser)
|
||||
apiRouter.HandlerFunc(http.MethodPut, "/v1/users/activated", api.ActivateUser)
|
||||
// Path parameters use {id} instead of :id
|
||||
apiMux.HandleFunc("GET /v1/issues", api.RequirePermission("issues:read", api.ListIssues))
|
||||
apiMux.HandleFunc("POST /v1/issues", api.RequirePermission("issues:write", api.CreateIssue))
|
||||
apiMux.HandleFunc("GET /v1/issues/{id}", api.RequirePermission("issues:read", api.ReadIssue))
|
||||
apiMux.HandleFunc("PATCH /v1/issues/{id}", api.RequirePermission("issues:write", api.UpdateIssue))
|
||||
apiMux.HandleFunc("DELETE /v1/issues/{id}", api.RequirePermission("issues:write", api.DeleteIssue))
|
||||
apiMux.HandleFunc("GET /v1/issues/{id}/pubkey", api.RequirePermission("issues:read", api.ReadIssuePubKey))
|
||||
apiMux.HandleFunc("POST /v1/issues/{id}/blind-sign", api.RequirePermission("issues:read", api.BlindSignIssueVote))
|
||||
|
||||
apiMux.HandleFunc("POST /v1/votes", api.Vote)
|
||||
apiMux.HandleFunc("POST /v1/users", api.CreateUser)
|
||||
apiMux.HandleFunc("GET /v1/users", api.RequirePermission("users:read", api.ListUsers))
|
||||
apiMux.HandleFunc("GET /v1/users/{id}", api.RequireAuthenticatedUser(api.ReadUser))
|
||||
apiMux.HandleFunc("DELETE /v1/users/{id}", api.DeleteUser)
|
||||
apiMux.HandleFunc("PUT /v1/users/activated", api.ActivateUser)
|
||||
|
||||
apiRouter.HandlerFunc(http.MethodPost, "/v1/tokens/authentication", api.CreateAuthenticationToken)
|
||||
apiRouter.HandlerFunc(http.MethodDelete, "/v1/tokens/authentication", api.RequireAuthenticatedUser(api.DeleteAuthenticationToken))
|
||||
apiMux.HandleFunc("POST /v1/tokens/authentication", api.CreateAuthenticationToken)
|
||||
apiMux.HandleFunc("DELETE /v1/tokens/authentication", api.RequireAuthenticatedUser(api.DeleteAuthenticationToken))
|
||||
|
||||
apiRouter.HandlerFunc(http.MethodPost, "/v1/device-tokens", api.RequireAuthenticatedUser(api.RegisterDeviceToken))
|
||||
apiRouter.HandlerFunc(http.MethodDelete, "/v1/device-tokens", api.RequireAuthenticatedUser(api.DeleteDeviceToken))
|
||||
apiMux.HandleFunc("POST /v1/device-tokens", api.RequireAuthenticatedUser(api.RegisterDeviceToken))
|
||||
apiMux.HandleFunc("DELETE /v1/device-tokens", api.RequireAuthenticatedUser(api.DeleteDeviceToken))
|
||||
|
||||
apiRouter.HandlerFunc(http.MethodGet, "/v1/mps", api.ListMPs)
|
||||
apiRouter.HandlerFunc(http.MethodGet, "/v1/parlament/votes", api.ListParlVotes)
|
||||
apiRouter.Handler(http.MethodGet, "/v1/parlament/votes/*path", http.HandlerFunc(api.GetParlVoteDetail))
|
||||
apiMux.HandleFunc("GET /v1/mps", api.ListMPs)
|
||||
apiMux.HandleFunc("GET /v1/parlament/votes", api.ListParlVotes)
|
||||
|
||||
// Wildcards use {name...}
|
||||
apiMux.HandleFunc("GET /v1/parlament/votes/{path...}", api.GetParlVoteDetail)
|
||||
apiMux.Handle("GET /debug/vars", expvar.Handler())
|
||||
|
||||
apiRouter.Handler(http.MethodGet, "/debug/vars", expvar.Handler())
|
||||
apiChain := app.Metrics(api.RecoverPanic(app.EnableCORS(api.RateLimit(api.Authenticate(apiMux)))))
|
||||
|
||||
apiChain := app.Metrics(api.RecoverPanic(app.EnableCORS(api.RateLimit(api.Authenticate(apiRouter)))))
|
||||
|
||||
// ── Web router (cookie auth) ─────────────────────────────────────────────
|
||||
|
||||
web := web.Web{
|
||||
// ── Web router ──────────────────────────────────────────────────────────
|
||||
web := web.Web{
|
||||
App: app,
|
||||
}
|
||||
webMux := http.NewServeMux()
|
||||
|
||||
webRouter := httprouter.New()
|
||||
webRouter.HandlerFunc(http.MethodGet, "/", web.Home)
|
||||
webRouter.HandlerFunc(http.MethodGet, "/register", web.Register)
|
||||
webRouter.HandlerFunc(http.MethodPost, "/register", web.RegisterUserPage)
|
||||
webRouter.HandlerFunc(http.MethodGet, "/issues", web.IssuesPage)
|
||||
webRouter.HandlerFunc(http.MethodPost, "/issues", web.CreateIssueAction)
|
||||
webRouter.HandlerFunc(http.MethodGet, "/issues/:id", web.IssuePage)
|
||||
webRouter.HandlerFunc(http.MethodPatch, "/issues/:id", web.UpdateIssueAction)
|
||||
webRouter.HandlerFunc(http.MethodDelete, "/issues/:id", web.DeleteIssueAction)
|
||||
webRouter.HandlerFunc(http.MethodGet, "/issues/:id/pubkey", web.GetIssuePubKey)
|
||||
webRouter.HandlerFunc(http.MethodPost, "/issues/:id/blind-sign", web.BlindSignIssue)
|
||||
webRouter.HandlerFunc(http.MethodPost, "/votes", web.VoteAction)
|
||||
webRouter.HandlerFunc(http.MethodGet, "/users", web.UsersPage)
|
||||
webRouter.HandlerFunc(http.MethodGet, "/users/me", web.ProfilePage)
|
||||
webRouter.HandlerFunc(http.MethodGet, "/users/activated", web.ActivatePage)
|
||||
webRouter.HandlerFunc(http.MethodPost, "/users/activated", web.ActivateUserAction)
|
||||
webRouter.HandlerFunc(http.MethodDelete, "/users/:id", web.DeleteUserAction)
|
||||
webRouter.HandlerFunc(http.MethodGet, "/mps", web.MembersOfParliamentPage)
|
||||
webRouter.HandlerFunc(http.MethodGet, "/parlament", web.ParlVotesPage)
|
||||
webRouter.Handler(http.MethodGet, "/parlament/*path", http.HandlerFunc(web.ParlamentDispatch))
|
||||
webRouter.HandlerFunc(http.MethodPost, "/login", web.Login)
|
||||
webRouter.HandlerFunc(http.MethodPost, "/dev-login", web.DevLogin)
|
||||
webRouter.HandlerFunc(http.MethodPost, "/logout", web.Logout)
|
||||
webRouter.HandlerFunc(http.MethodGet, "/ws", ws)
|
||||
webRouter.ServeFiles("/static/*filepath", http.Dir("web/static"))
|
||||
webMux.HandleFunc("GET /", web.Home)
|
||||
webMux.HandleFunc("GET /register", web.Register)
|
||||
webMux.HandleFunc("POST /register", web.RegisterUserPage)
|
||||
webMux.HandleFunc("GET /issues", web.IssuesPage)
|
||||
webMux.HandleFunc("POST /issues", web.CreateIssueAction)
|
||||
webMux.HandleFunc("GET /issues/{id}", web.IssuePage)
|
||||
webMux.HandleFunc("PATCH /issues/{id}", web.UpdateIssueAction)
|
||||
webMux.HandleFunc("DELETE /issues/{id}", web.DeleteIssueAction)
|
||||
webMux.HandleFunc("GET /issues/{id}/pubkey", web.GetIssuePubKey)
|
||||
webMux.HandleFunc("POST /issues/{id}/blind-sign", web.BlindSignIssue)
|
||||
webMux.HandleFunc("POST /votes", web.VoteAction)
|
||||
webMux.HandleFunc("GET /users", web.UsersPage)
|
||||
webMux.HandleFunc("GET /users/me", web.ProfilePage)
|
||||
webMux.HandleFunc("GET /users/activated", web.ActivatePage)
|
||||
webMux.HandleFunc("POST /users/activated", web.ActivateUserAction)
|
||||
webMux.HandleFunc("DELETE /users/{id}", web.DeleteUserAction)
|
||||
webMux.HandleFunc("GET /mps", web.MembersOfParliamentPage)
|
||||
webMux.HandleFunc("GET /parlament", web.ParlVotesPage)
|
||||
webMux.HandleFunc("GET /parlament/{path...}", web.ParlamentDispatch)
|
||||
webMux.HandleFunc("POST /login", web.Login)
|
||||
webMux.HandleFunc("POST /dev-login", web.DevLogin)
|
||||
webMux.HandleFunc("POST /logout", web.Logout)
|
||||
webMux.HandleFunc("GET /ws", ws)
|
||||
|
||||
// Static files in standard library
|
||||
fileServer := http.FileServer(http.Dir("web/static"))
|
||||
webMux.Handle("GET /static/", http.StripPrefix("/static/", fileServer))
|
||||
|
||||
webChain := app.Metrics(web.WebRecoverPanic(web.WebRateLimit(web.AuthenticateCookie(webRouter))))
|
||||
webChain := app.Metrics(web.WebRecoverPanic(web.WebRateLimit(web.AuthenticateCookie(webMux))))
|
||||
|
||||
// ── Top-level mux ────────────────────────────────────────────────────────
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/v1/", apiChain)
|
||||
mux.Handle("/debug/", apiChain)
|
||||
mux.Handle("/", webChain)
|
||||
// ── Top-level mux ────────────────────────────────────────────────────────
|
||||
mainMux := http.NewServeMux()
|
||||
mainMux.Handle("/v1/", apiChain)
|
||||
mainMux.Handle("/debug/", apiChain)
|
||||
mainMux.Handle("/", webChain)
|
||||
|
||||
return mux
|
||||
}
|
||||
return mainMux
|
||||
}
|
||||
@@ -3,14 +3,12 @@ package web
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"party.at/party/cmd/party/parlament"
|
||||
"party.at/party/internal/data"
|
||||
)
|
||||
|
||||
func (web *Web) ParlamentDispatch(w http.ResponseWriter, r *http.Request) {
|
||||
ps := httprouter.ParamsFromContext(r.Context())
|
||||
if ps.ByName("path") == "/rows" {
|
||||
if r.PathValue("path") == "/rows" {
|
||||
web.ParlVotesRowsFragment(w, r)
|
||||
return
|
||||
}
|
||||
@@ -18,8 +16,7 @@ func (web *Web) ParlamentDispatch(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (web *Web) ParlVoteDetailPage(w http.ResponseWriter, r *http.Request) {
|
||||
ps := httprouter.ParamsFromContext(r.Context())
|
||||
routePath := ps.ByName("path") // e.g. "/XXVIII/I/14"
|
||||
routePath := r.PathValue("path") // e.g. "/XXVIII/I/14"
|
||||
if routePath == "" || routePath == "/" {
|
||||
http.Error(w, "Bad Request", http.StatusBadRequest)
|
||||
return
|
||||
|
||||
Reference in new issue
Block a user