Files
lazyhandler/magic/response.go
2025-06-18 10:12:19 +08:00

62 lines
1.3 KiB
Go

package magic
import (
"encoding/json"
"net/http"
"github.com/gorilla/websocket"
)
type RespondWriter interface {
WriteResponse(http.ResponseWriter)
}
type RespondWriterFunc func(http.ResponseWriter)
func (fn RespondWriterFunc) WriteResponse(w http.ResponseWriter) {
fn(w)
}
type ErrorResponse interface {
error
WriteResponse(http.ResponseWriter)
}
func WrapSimpleErrorWithStatus(message string, status int) ErrorResponse {
return simpleErrorResponseWithoutBody{
message: message,
status: status,
}
}
type simpleErrorResponseWithoutBody struct {
message string
status int
}
func (err simpleErrorResponseWithoutBody) Error() string {
return err.message
}
func (err simpleErrorResponseWithoutBody) WriteResponse(w http.ResponseWriter) {
w.WriteHeader(err.status)
}
func init() {
RegisterExtractorThatTakesResponseWriterGeneric[http.ResponseWriter](func(w http.ResponseWriter, r *http.Request) (any, error) {
return w, nil
})
upgrader := &websocket.Upgrader{
Error: func(w http.ResponseWriter, r *http.Request, status int, reason error) {
w.WriteHeader(status)
json.NewEncoder(w).Encode(Map{
"error": reason.Error(),
})
},
}
RegisterExtractorThatTakesResponseWriterGeneric[*websocket.Conn](func(w http.ResponseWriter, r *http.Request) (any, error) {
return upgrader.Upgrade(w, r, nil)
})
}