|
| 1 | +//go:build testintegration |
| 2 | + |
| 3 | +package api |
| 4 | + |
| 5 | +import ( |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "net/http" |
| 9 | + "strconv" |
| 10 | +) |
| 11 | + |
| 12 | +type User struct { |
| 13 | + Name string `json:"name"` |
| 14 | + Age int `json:"age"` |
| 15 | +} |
| 16 | + |
| 17 | +// FooBarRequest represents body of FooBar request. |
| 18 | +type FooBarRequest struct { |
| 19 | + // Foo param |
| 20 | + Foo string `json:"foo"` |
| 21 | + // Bar params |
| 22 | + Bar []int `json:"bar"` |
| 23 | + // User param |
| 24 | + User User `json:"user"` |
| 25 | +} |
| 26 | + |
| 27 | +// FooBarResponse represents body of FooBar response. |
| 28 | +type FooBarResponse struct { |
| 29 | + Baz struct { |
| 30 | + Prop string `json:"prop"` |
| 31 | + } `json:"baz"` |
| 32 | +} |
| 33 | + |
| 34 | +// FooBarHandler handles incoming foobar requests |
| 35 | +func FooBarHandler(w http.ResponseWriter, req *http.Request) { |
| 36 | + if err := req.ParseForm(); err != nil { |
| 37 | + http.Error(w, fmt.Sprintf("%s: %v", http.StatusText(http.StatusBadRequest), err), http.StatusBadRequest) |
| 38 | + return |
| 39 | + } |
| 40 | + raw := req.FormValue("age") |
| 41 | + age, err := strconv.Atoi(raw) |
| 42 | + if err != nil { |
| 43 | + http.Error(w, fmt.Sprintf("%s: %v", http.StatusText(http.StatusBadRequest), err), http.StatusBadRequest) |
| 44 | + return |
| 45 | + } |
| 46 | + |
| 47 | + r := FooBarRequest{ |
| 48 | + Foo: req.FormValue("foo"), |
| 49 | + User: User{ |
| 50 | + Name: req.FormValue("name"), |
| 51 | + Age: age, |
| 52 | + }, |
| 53 | + } |
| 54 | + |
| 55 | + resp := doSthWithRequest(r) |
| 56 | + |
| 57 | + enc := json.NewEncoder(w) |
| 58 | + err = enc.Encode(resp) |
| 59 | + if err != nil { |
| 60 | + http.Error(w, fmt.Sprintf("%s: %v", http.StatusText(http.StatusInternalServerError), err), http.StatusInternalServerError) |
| 61 | + return |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +func doSthWithRequest(req FooBarRequest) FooBarResponse { |
| 66 | + return FooBarResponse{} |
| 67 | +} |
0 commit comments