Files
houston/server/http_handler.go

88 lines
1.6 KiB
Go
Raw Normal View History

2023-05-22 00:54:49 +09:00
package server
import (
"go-ayo/common"
"go-ayo/logger"
"io"
"net/http"
"reflect"
"runtime/debug"
"strings"
)
const (
defaultMaxMemory = 32 << 10 // 32 KB
)
type HoustonServerWithHandler interface {
HoustonServer
RegisterHandlers(serveMux *http.ServeMux, prefix string) error
}
type houstonHandler struct {
HoustonServer
methods map[string]reflect.Method
}
func NewHoustonHandler() HoustonServerWithHandler {
var tmp *houstonHandler
methods := make(map[string]reflect.Method)
tp := reflect.TypeOf(tmp)
for i := 0; i < tp.NumMethod(); i++ {
method := tp.Method(i)
methods[strings.ToLower(method.Name)] = method
}
return &houstonHandler{
HoustonServer: NewServer(),
methods: methods,
}
}
func (h *houstonHandler) RegisterHandlers(serveMux *http.ServeMux, prefix string) error {
serveMux.Handle(common.MakeHttpHandlerPattern(prefix, "houston"), h)
return nil
}
func (h *houstonHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() {
s := recover()
if s != nil {
logger.Println(s)
debug.PrintStack()
}
}()
defer func() {
io.Copy(io.Discard, r.Body)
r.Body.Close()
}()
operation := r.FormValue("operation")
if len(operation) == 0 {
w.WriteHeader(http.StatusBadRequest)
return
}
method, ok := h.methods[strings.ToLower(operation)]
if !ok {
// 없는 operation
logger.Println("fail to call api. operation is not valid :", operation)
w.WriteHeader(http.StatusBadRequest)
return
}
if r.PostForm == nil {
r.ParseMultipartForm(defaultMaxMemory)
}
args := []reflect.Value{
reflect.ValueOf(h),
reflect.ValueOf(w),
reflect.ValueOf(r),
}
method.Func.Call(args)
}