handler.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. "net/http"
  18. "github.com/fatedier/frp/pkg/util/log"
  19. )
  20. type GeneralResponse struct {
  21. Code int
  22. Msg string
  23. }
  24. // APIHandler is a handler function that returns a response object or an error.
  25. type APIHandler func(ctx *Context) (any, error)
  26. // MakeHTTPHandlerFunc turns a normal APIHandler into a http.HandlerFunc.
  27. func MakeHTTPHandlerFunc(handler APIHandler) http.HandlerFunc {
  28. return func(w http.ResponseWriter, r *http.Request) {
  29. ctx := NewContext(w, r)
  30. res, err := handler(ctx)
  31. if err != nil {
  32. log.Warnf("http response [%s]: error: %v", r.URL.Path, err)
  33. code := http.StatusInternalServerError
  34. if e, ok := err.(*Error); ok {
  35. code = e.Code
  36. }
  37. w.Header().Set("Content-Type", "application/json")
  38. w.WriteHeader(code)
  39. _ = json.NewEncoder(w).Encode(GeneralResponse{Code: code, Msg: err.Error()})
  40. return
  41. }
  42. if res == nil {
  43. w.WriteHeader(http.StatusOK)
  44. return
  45. }
  46. switch v := res.(type) {
  47. case []byte:
  48. _, _ = w.Write(v)
  49. case string:
  50. _, _ = w.Write([]byte(v))
  51. default:
  52. w.Header().Set("Content-Type", "application/json")
  53. w.WriteHeader(http.StatusOK)
  54. _ = json.NewEncoder(w).Encode(v)
  55. }
  56. }
  57. }