pages-server/server/context/context.go

65 lines
1.2 KiB
Go
Raw Normal View History

2022-07-27 15:25:08 +00:00
package context
import (
stdContext "context"
2022-08-28 14:21:37 +00:00
"io"
2022-07-27 15:25:08 +00:00
"net/http"
2022-08-28 14:21:37 +00:00
"strings"
2022-07-27 15:25:08 +00:00
)
type Context struct {
RespWriter http.ResponseWriter
Req *http.Request
StatusCode int
2022-07-27 15:25:08 +00:00
}
2022-08-28 13:33:10 +00:00
func New(w http.ResponseWriter, r *http.Request) *Context {
return &Context{
RespWriter: w,
Req: r,
StatusCode: http.StatusOK,
2022-08-28 13:33:10 +00:00
}
}
2022-07-27 15:25:08 +00:00
func (c *Context) Context() stdContext.Context {
if c.Req != nil {
return c.Req.Context()
}
return stdContext.Background()
}
func (c *Context) Response() *http.Response {
if c.Req != nil && c.Req.Response != nil {
2022-07-27 15:25:08 +00:00
return c.Req.Response
}
return nil
}
2022-08-28 13:09:54 +00:00
2022-08-28 14:21:37 +00:00
func (c *Context) String(raw string, status ...int) {
code := http.StatusOK
if len(status) != 0 {
code = status[0]
}
c.RespWriter.WriteHeader(code)
2022-08-28 14:53:30 +00:00
_, _ = io.Copy(c.RespWriter, strings.NewReader(raw))
2022-08-28 14:21:37 +00:00
}
func (c *Context) IsMethod(m string) bool {
return c.Req.Method == m
}
2022-08-28 13:09:54 +00:00
func (c *Context) Redirect(uri string, statusCode int) {
http.Redirect(c.RespWriter, c.Req, uri, statusCode)
}
2022-08-28 13:33:10 +00:00
// Path returns requested path.
//
// The returned bytes are valid until your request handler returns.
func (c *Context) Path() string {
return c.Req.URL.Path
}
2022-08-28 14:21:37 +00:00
func (c *Context) Host() string {
return c.Req.URL.Host
}