|
| 1 | +package httpx |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "io" |
| 6 | + "net/http" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "github.com/moukoublen/goboilerplate/build" |
| 10 | + "github.com/moukoublen/goboilerplate/internal/logx" |
| 11 | +) |
| 12 | + |
| 13 | +func AboutHandler(w http.ResponseWriter, r *http.Request) { |
| 14 | + RespondJSON(r.Context(), w, http.StatusOK, build.GetInfo()) |
| 15 | +} |
| 16 | + |
| 17 | +func EchoHandler(w http.ResponseWriter, r *http.Request) { |
| 18 | + var cErr error |
| 19 | + defer DrainAndCloseRequest(r, &cErr) |
| 20 | + |
| 21 | + logger := logx.GetFromContext(r.Context()) |
| 22 | + |
| 23 | + if h := r.Header.Get("X-Auth-Key"); h != `_Named must your fear be before banish it you can_` { |
| 24 | + w.WriteHeader(http.StatusUnauthorized) |
| 25 | + return |
| 26 | + } |
| 27 | + |
| 28 | + b := map[string]any{} |
| 29 | + { |
| 30 | + b["method"] = r.Method |
| 31 | + b["proto"] = r.Proto |
| 32 | + b["protoMajor"] = r.ProtoMajor |
| 33 | + b["protoMinor"] = r.ProtoMinor |
| 34 | + |
| 35 | + if r.URL != nil { |
| 36 | + u := map[string]any{} |
| 37 | + u["scheme"] = r.URL.Scheme |
| 38 | + u["opaque"] = r.URL.Opaque |
| 39 | + u["user"] = r.URL.User |
| 40 | + u["host"] = r.URL.Host |
| 41 | + u["path"] = r.URL.Path |
| 42 | + u["rawPath"] = r.URL.RawPath |
| 43 | + u["omitHost"] = r.URL.OmitHost |
| 44 | + u["forceQuery"] = r.URL.ForceQuery |
| 45 | + u["rawQuery"] = r.URL.RawQuery |
| 46 | + u["fragment"] = r.URL.Fragment |
| 47 | + u["rawFragment"] = r.URL.RawFragment |
| 48 | + } |
| 49 | + |
| 50 | + headers := map[string]string{} |
| 51 | + for k := range r.Header { |
| 52 | + headers[k] = r.Header.Get(k) |
| 53 | + } |
| 54 | + b["headers"] = headers |
| 55 | + |
| 56 | + if ct := r.Header.Get("Content-Type"); strings.Contains(ct, "application/json") { |
| 57 | + body := map[string]any{} |
| 58 | + _ = json.NewDecoder(r.Body).Decode(&body) |
| 59 | + b["body"] = body |
| 60 | + } else { |
| 61 | + body, _ := io.ReadAll(r.Body) |
| 62 | + b["body"] = body |
| 63 | + } |
| 64 | + |
| 65 | + b["contentLength"] = r.ContentLength |
| 66 | + b["transferEncoding"] = r.TransferEncoding |
| 67 | + b["host"] = r.Host |
| 68 | + |
| 69 | + trailer := map[string]string{} |
| 70 | + for k := range r.Trailer { |
| 71 | + trailer[k] = r.Header.Get(k) |
| 72 | + } |
| 73 | + b["trailer"] = trailer |
| 74 | + |
| 75 | + b["remoteAddr"] = r.RemoteAddr |
| 76 | + b["requestURI"] = r.RequestURI |
| 77 | + } |
| 78 | + |
| 79 | + w.Header().Add("Content-Type", "application/json") |
| 80 | + w.WriteHeader(http.StatusOK) |
| 81 | + err := json.NewEncoder(w).Encode(b) |
| 82 | + if err != nil { |
| 83 | + logger.Error("error during json encoding", logx.Error(err)) |
| 84 | + } |
| 85 | +} |
0 commit comments