| 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 | |
| 15 | package http |
| 16 | |
| 17 | import ( |
| 18 | "encoding/json" |
| 19 | "io" |
| 20 | "net/http" |
| 21 | |
| 22 | "github.com/gorilla/mux" |
| 23 | ) |
| 24 | |
| 25 | type Context struct { |
| 26 | Req *http.Request |
| 27 | Resp http.ResponseWriter |
| 28 | vars map[string]string |
| 29 | } |
| 30 | |
| 31 | func NewContext(w http.ResponseWriter, r *http.Request) *Context { |
| 32 | return &Context{ |
| 33 | Req: r, |
| 34 | Resp: w, |
| 35 | vars: mux.Vars(r), |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | func (c *Context) Param(key string) string { |
| 40 | return c.vars[key] |
| 41 | } |
| 42 | |
| 43 | func (c *Context) Query(key string) string { |
| 44 | return c.Req.URL.Query().Get(key) |
| 45 | } |
| 46 | |
| 47 | func (c *Context) BindJSON(obj any) error { |
| 48 | body, err := io.ReadAll(c.Req.Body) |
| 49 | if err != nil { |
| 50 | return err |
| 51 | } |
| 52 | return json.Unmarshal(body, obj) |
| 53 | } |
| 54 | |
| 55 | func (c *Context) Body() ([]byte, error) { |
| 56 | return io.ReadAll(c.Req.Body) |
| 57 | } |