123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204 |
- package http
- import (
- "context"
- "encoding/json"
- "net"
- "net/http"
- "os"
- "path"
- "strings"
- )
- var (
- defaultBinder = &DefaultBinder{}
- )
- var (
- realIPHeaders = []string{
- "Cf-Connecting-Ip",
- "True-Client-IP",
- "X-Forwarded-For",
- "X-Real-Ip",
- }
- )
- type Context struct {
- ctx context.Context
- req *http.Request
- res http.ResponseWriter
- params map[string]string
- user *Userinfo
- statusCode int
- }
- func (ctx *Context) reset(req *http.Request, res http.ResponseWriter, ps map[string]string) {
- ctx.statusCode = http.StatusOK
- ctx.user = nil
- ctx.req, ctx.res, ctx.params = req, res, ps
- }
- func (ctx *Context) User() *Userinfo {
- return ctx.user
- }
- func (ctx *Context) SetUser(ui *Userinfo) {
- ctx.user = ui
- }
- func (ctx *Context) RealIp() string {
- var (
- s string
- pos int
- ipaddr string
- )
- for _, h := range realIPHeaders {
- if ipaddr = ctx.Request().Header.Get(h); ipaddr != "" {
- goto __end
- }
- }
- ipaddr, _, _ = net.SplitHostPort(ctx.Request().RemoteAddr)
- __end:
- for {
- if pos = strings.IndexByte(ipaddr, ','); pos > -1 {
- s = strings.TrimSpace(ipaddr[:pos])
- if netAddr := net.ParseIP(s); netAddr != nil && !netAddr.IsPrivate() {
- return s
- }
- ipaddr = ipaddr[pos+1:]
- } else {
- break
- }
- }
- return strings.TrimSpace(ipaddr)
- }
- func (ctx *Context) Request() *http.Request {
- return ctx.req
- }
- func (ctx *Context) Response() http.ResponseWriter {
- return ctx.res
- }
- func (ctx *Context) Context() context.Context {
- if ctx.Request().Context() != nil {
- return ctx.Request().Context()
- }
- return ctx.ctx
- }
- func (ctx *Context) Bind(v any) (err error) {
- return defaultBinder.Bind(v, ctx.Request())
- }
- func (ctx *Context) Query(k string) string {
- qs := ctx.Request().URL.Query()
- if qs == nil {
- return ""
- }
- return qs.Get(k)
- }
- func (ctx *Context) Form(k string) string {
- return ctx.Request().FormValue(k)
- }
- func (ctx *Context) Param(k string) string {
- var (
- ok bool
- s string
- )
- if s, ok = ctx.params[k]; ok {
- return s
- }
- s = ctx.Query(k)
- if s == "" {
- s = ctx.Form(k)
- }
- return s
- }
- func (ctx *Context) json(res responsePayload) (err error) {
- ctx.Response().Header().Set("Content-Type", "application/json")
- encoder := json.NewEncoder(ctx.Response())
- if strings.HasPrefix(ctx.Request().Header.Get("User-Agent"), "curl") {
- encoder.SetIndent("", "\t")
- }
- return encoder.Encode(res)
- }
- func (ctx *Context) Success(v any) (err error) {
- return ctx.json(responsePayload{Data: v})
- }
- func (ctx *Context) Status(code int) {
- ctx.statusCode = code
- }
- func (ctx *Context) Error(code int, reason string) (err error) {
- return ctx.json(responsePayload{Code: code, Reason: reason})
- }
- func (ctx *Context) Redirect(url string, code int) {
- if code != http.StatusFound && code != http.StatusMovedPermanently {
- code = http.StatusFound
- }
- http.Redirect(ctx.Response(), ctx.Request(), url, code)
- }
- func (ctx *Context) SetCookie(cookie *http.Cookie) {
- http.SetCookie(ctx.Response(), cookie)
- }
- func (ctx *Context) GetCookie(name string) (*http.Cookie, error) {
- return ctx.Request().Cookie(name)
- }
- func (ctx *Context) DeleteCookie(name string) {
- cookie, err := ctx.GetCookie(name)
- if err == nil {
- cookie.MaxAge = -1
- ctx.SetCookie(cookie)
- }
- }
- func (ctx *Context) SetCookieValue(name, value, domain string) {
- if domain == "" {
- domain = ctx.Request().URL.Hostname()
- }
- if name == "" || value == "" {
- return
- }
- ctx.SetCookie(&http.Cookie{
- Name: name,
- Value: value,
- Path: "/",
- Domain: domain,
- })
- }
- func (ctx *Context) GetCookieValue(name string) string {
- if name == "" {
- return ""
- }
- cookie, err := ctx.GetCookie(name)
- if err == nil {
- return cookie.Value
- }
- return ""
- }
- func (ctx *Context) SendFile(filename string) (err error) {
- var (
- fi os.FileInfo
- fp *os.File
- )
- if fi, err = os.Stat(filename); err == nil {
- if fp, err = os.Open(filename); err == nil {
- http.ServeContent(ctx.Response(), ctx.Request(), path.Base(filename), fi.ModTime(), fp)
- err = fp.Close()
- }
- }
- return
- }
|