1
0

context.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2025 The frp Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package http
  15. import (
  16. "encoding/json"
  17. "io"
  18. "net/http"
  19. "github.com/gorilla/mux"
  20. )
  21. type Context struct {
  22. Req *http.Request
  23. Resp http.ResponseWriter
  24. vars map[string]string
  25. }
  26. func NewContext(w http.ResponseWriter, r *http.Request) *Context {
  27. return &Context{
  28. Req: r,
  29. Resp: w,
  30. vars: mux.Vars(r),
  31. }
  32. }
  33. func (c *Context) Param(key string) string {
  34. return c.vars[key]
  35. }
  36. func (c *Context) Query(key string) string {
  37. return c.Req.URL.Query().Get(key)
  38. }
  39. func (c *Context) BindJSON(obj any) error {
  40. body, err := io.ReadAll(c.Req.Body)
  41. if err != nil {
  42. return err
  43. }
  44. return json.Unmarshal(body, obj)
  45. }
  46. func (c *Context) Body() ([]byte, error) {
  47. return io.ReadAll(c.Req.Body)
  48. }