http_server.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. package fairwind
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net"
  7. "net/http"
  8. "reflect"
  9. "time"
  10. )
  11. type HTTPServerRequest struct {
  12. Headers HTTPHeaders
  13. Data any
  14. }
  15. type HTTPServerResponse struct {
  16. Headers HTTPHeaders
  17. Status int
  18. Error error
  19. Encoding int
  20. Plain []byte
  21. Data any
  22. }
  23. func ResponseOK() *HTTPServerResponse {
  24. return &HTTPServerResponse{
  25. Headers: HTTPHeaders{},
  26. Plain: []byte{},
  27. Encoding: ENCODING_PLAIN,
  28. }
  29. }
  30. func ResponsePlain(headers HTTPHeaders, plain []byte) *HTTPServerResponse {
  31. return &HTTPServerResponse{
  32. Headers: headers,
  33. Plain: plain,
  34. Encoding: ENCODING_PLAIN,
  35. }
  36. }
  37. func ResponseJSON(headers HTTPHeaders, data any) *HTTPServerResponse {
  38. return &HTTPServerResponse{
  39. Headers: headers,
  40. Data: data,
  41. Encoding: ENCODING_JSON,
  42. }
  43. }
  44. func ResponseErr(status int, err error) *HTTPServerResponse {
  45. return &HTTPServerResponse{
  46. Status: status,
  47. Error: err,
  48. }
  49. }
  50. type HTTPServerCallback func(request *HTTPServerRequest) *HTTPServerResponse
  51. type HTTPServerHandler struct {
  52. Callback HTTPServerCallback
  53. Data any
  54. Buffer int
  55. }
  56. type HTTPServerAction struct {
  57. Method int
  58. Path string
  59. }
  60. type HTTPServer struct {
  61. log *Log
  62. host string
  63. port string
  64. handlers map[HTTPServerAction]HTTPServerHandler
  65. }
  66. func NewHTTPServer(log *Log, host string, port string, handlers map[HTTPServerAction]HTTPServerHandler) *HTTPServer {
  67. return &HTTPServer{
  68. log: log,
  69. host: host,
  70. port: port,
  71. handlers: handlers,
  72. }
  73. }
  74. func (this *HTTPServer) Start() error {
  75. listener, err := net.Listen("tcp", fmt.Sprintf("%s:%s", this.host, this.port))
  76. if err != nil {
  77. return err
  78. }
  79. channel := make(chan error)
  80. go func(listener net.Listener, channel chan<- error) {
  81. server := &http.Server{
  82. Handler: this,
  83. }
  84. channel <- server.Serve(listener)
  85. }(listener, channel)
  86. err = <-channel
  87. if err != nil {
  88. return err
  89. }
  90. return nil
  91. }
  92. func (this *HTTPServer) ServeHTTP(responseStream http.ResponseWriter, requestStream *http.Request) {
  93. // Find handler
  94. method := METHOD_NONE
  95. switch requestStream.Method {
  96. case "GET":
  97. method = METHOD_GET
  98. case "POST":
  99. method = METHOD_POST
  100. }
  101. if method == METHOD_NONE {
  102. this.log.Error("invalid method", LogValue("method", requestStream.Method))
  103. responseStream.WriteHeader(http.StatusInternalServerError)
  104. return
  105. }
  106. handlerSpec, ok := this.handlers[HTTPServerAction{Method: method, Path: requestStream.URL.Path}]
  107. if !ok {
  108. this.log.Error("handler not found", LogValue("path", requestStream.URL.Path))
  109. responseStream.WriteHeader(http.StatusInternalServerError)
  110. return
  111. }
  112. handler := HTTPServerHandler{}
  113. copyStruct(&handler, &handlerSpec)
  114. handlerSpec = handler
  115. // Parse GET query
  116. if method == METHOD_GET && handler.Data != nil {
  117. query := map[string]any{}
  118. for key, values := range requestStream.URL.Query() {
  119. for _, value := range values {
  120. query[key] = value
  121. }
  122. }
  123. buffer, err := json.Marshal(query)
  124. if err != nil {
  125. this.log.Error("malformed request body", LogValue("path", requestStream.URL.Path), LogError(err))
  126. responseStream.WriteHeader(http.StatusInternalServerError)
  127. return
  128. }
  129. err = json.Unmarshal(buffer, &handler.Data)
  130. if err != nil {
  131. this.log.Error("malformed request body", LogValue("path", requestStream.URL.Path), LogError(err))
  132. responseStream.WriteHeader(http.StatusInternalServerError)
  133. return
  134. }
  135. }
  136. // Parse POST body
  137. if method == METHOD_POST && handler.Data != nil {
  138. size := 1
  139. if handler.Buffer > 0 {
  140. size = handler.Buffer
  141. }
  142. buffer := make([]byte, 1024*size)
  143. n, err := requestStream.Body.Read(buffer)
  144. if err != io.EOF {
  145. this.log.Error("malformed request body", LogValue("path", requestStream.URL.Path), LogError(err))
  146. responseStream.WriteHeader(http.StatusInternalServerError)
  147. return
  148. }
  149. err = json.Unmarshal(buffer[:n], &handler.Data)
  150. if err != nil {
  151. this.log.Error("malformed request body", LogValue("path", requestStream.URL.Path), LogError(err))
  152. responseStream.WriteHeader(http.StatusInternalServerError)
  153. return
  154. }
  155. }
  156. // Log query
  157. start := time.Now()
  158. defer func() {
  159. this.log.Debug(
  160. "request",
  161. LogValue("method", requestStream.Method),
  162. LogValue("path", requestStream.URL.Path),
  163. LogValue("duration", time.Since(start)),
  164. )
  165. }()
  166. // Handle
  167. requestHeaders := HTTPHeaders{}
  168. for key, values := range requestStream.Header {
  169. for _, value := range values {
  170. requestHeaders[key] = value
  171. }
  172. }
  173. response := handler.Callback(
  174. &HTTPServerRequest{
  175. Headers: requestHeaders,
  176. Data: handler.Data,
  177. },
  178. )
  179. if response.Error != nil {
  180. this.log.Error("error serving request", LogError(response.Error))
  181. }
  182. // Headers
  183. for key, value := range response.Headers {
  184. responseStream.Header().Add(key, value)
  185. }
  186. if response.Encoding == ENCODING_PLAIN {
  187. responseStream.Header().Add("Content-Type", "text/plain")
  188. }
  189. if response.Encoding == ENCODING_JSON {
  190. responseStream.Header().Add("Content-Type", "application/json")
  191. }
  192. // Status
  193. if response.Status == 0 {
  194. responseStream.WriteHeader(http.StatusOK)
  195. } else {
  196. responseStream.WriteHeader(response.Status)
  197. }
  198. // Body
  199. if response.Encoding == ENCODING_PLAIN {
  200. _, err := responseStream.Write(response.Plain)
  201. if err != nil {
  202. this.log.Error("malformed response body", LogValue("path", requestStream.URL.Path), LogError(err))
  203. return
  204. }
  205. }
  206. if response.Encoding == ENCODING_JSON {
  207. buffer, err := json.Marshal(response.Data)
  208. if err != nil {
  209. this.log.Error("malformed response body", LogValue("path", requestStream.URL.Path), LogError(err))
  210. return
  211. }
  212. _, err = responseStream.Write(buffer)
  213. if err != nil {
  214. this.log.Error("malformed response body", LogValue("path", requestStream.URL.Path), LogError(err))
  215. return
  216. }
  217. }
  218. }
  219. func copyStruct(dst interface{}, src interface{}) {
  220. dstVal := reflect.ValueOf(dst)
  221. srcVal := reflect.ValueOf(src)
  222. if dstVal.Kind() != reflect.Ptr || dstVal.Elem().Kind() != reflect.Struct {
  223. return
  224. }
  225. if srcVal.Kind() == reflect.Ptr {
  226. srcVal = srcVal.Elem()
  227. }
  228. if srcVal.Kind() != reflect.Struct {
  229. return
  230. }
  231. dstVal = dstVal.Elem()
  232. for i := 0; i < srcVal.NumField(); i++ {
  233. srcField := srcVal.Field(i)
  234. fieldName := srcVal.Type().Field(i).Name
  235. dstField := dstVal.FieldByName(fieldName)
  236. if dstField.IsValid() && dstField.CanSet() && dstField.Type() == srcField.Type() {
  237. dstField.Set(srcField)
  238. }
  239. }
  240. }