Files
houston/server/http_handler.go

206 lines
5.5 KiB
Go
Raw Normal View History

2023-05-22 00:54:49 +09:00
package server
import (
2024-06-05 13:41:43 +09:00
"crypto/md5"
"encoding/hex"
2023-05-23 13:54:25 +09:00
"fmt"
2023-05-22 00:54:49 +09:00
"io"
"net/http"
2024-06-05 13:41:43 +09:00
"net/url"
2023-05-23 13:54:25 +09:00
"os"
2023-05-22 10:53:58 +09:00
"path"
2023-05-22 00:54:49 +09:00
"reflect"
"runtime/debug"
"strings"
2023-05-22 02:13:03 +09:00
2024-07-29 17:50:33 +09:00
"repositories.action2quare.com/ayo/gocommon"
2023-06-14 00:13:51 +09:00
"repositories.action2quare.com/ayo/gocommon/logger"
2023-05-22 00:54:49 +09:00
)
type HoustonServerWithHandler interface {
HoustonServer
2024-07-29 17:50:33 +09:00
RegisterHandlers(serveMux gocommon.ServerMuxInterface, prefix string) error
2023-05-22 00:54:49 +09:00
}
type houstonHandler struct {
HoustonServer
2024-09-23 17:46:39 +09:00
methods map[string]reflect.Method
deployPath string
downloadPath string
maingateApiToken string
2023-05-22 00:54:49 +09:00
}
2024-09-27 17:34:29 +09:00
func NewHoustonHandler(apiToken string) HoustonServerWithHandler {
2023-05-22 00:54:49 +09:00
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{
2024-09-23 17:46:39 +09:00
HoustonServer: NewServer(),
methods: methods,
2024-09-27 17:34:29 +09:00
maingateApiToken: apiToken,
2023-05-22 00:54:49 +09:00
}
}
2024-07-29 17:50:33 +09:00
func (h *houstonHandler) RegisterHandlers(serveMux gocommon.ServerMuxInterface, prefix string) error {
2023-06-22 17:15:56 +09:00
config := loadServerConfig()
storagePath := config.StorageRoot
h.deployPath = path.Join(storagePath, sub_folder_name_deploys)
h.downloadPath = path.Join(storagePath, sub_folder_name_downloads)
2023-06-13 11:18:22 +09:00
if err := os.MkdirAll(h.deployPath, 0775); err != nil {
return err
}
if err := os.MkdirAll(h.downloadPath, 0775); err != nil {
return err
}
2023-06-10 16:27:46 +09:00
if len(prefix) > 0 {
prefix = "/" + prefix
}
serveMux.Handle(prefix, h)
2023-05-22 00:54:49 +09:00
2023-06-13 11:04:30 +09:00
fsx := http.FileServer(http.Dir(h.deployPath))
2024-06-05 13:41:43 +09:00
deployPrefix := fmt.Sprintf("%s/%s/", prefix, sub_folder_name_deploys)
logger.Printf("houstonHandler registed. deployPath : %s -> %s", fmt.Sprintf("%s/%s/", prefix, sub_folder_name_deploys), h.deployPath)
serveMux.HandleFunc(fmt.Sprintf("%s/%s/", prefix, sub_folder_name_deploys), func(w http.ResponseWriter, r *http.Request) {
p := strings.TrimPrefix(r.URL.Path, deployPrefix)
rp := strings.TrimPrefix(r.URL.RawPath, deployPrefix)
h := md5.New()
src := strings.TrimLeft(r.URL.Path, fmt.Sprintf("/%s/", prefix))
h.Write([]byte(src))
at := hex.EncodeToString(h.Sum(nil))
if len(p) < len(r.URL.Path) && (r.URL.RawPath == "" || len(rp) < len(r.URL.RawPath)) && at == r.Header.Get("As-X-UrlHash") {
r2 := new(http.Request)
*r2 = *r
r2.URL = new(url.URL)
*r2.URL = *r.URL
r2.URL.Path = p
r2.URL.RawPath = rp
fsx.ServeHTTP(w, r2)
} else {
http.NotFound(w, r)
}
})
// config는 접근하기 편하게 단축 경로 제공
serveMux.HandleFunc("/config/", func(w http.ResponseWriter, r *http.Request) {
logger.Println("config url.path :", r.URL.Path)
2024-07-24 13:13:46 +09:00
testhash := md5.New()
testhash.Write([]byte(r.URL.Path))
at := hex.EncodeToString(testhash.Sum(nil))
2024-06-05 13:41:43 +09:00
hash := r.Header.Get("As-X-UrlHash")
logger.Println("config at = hash :", at, hash)
if at == hash {
urlpath := strings.TrimPrefix(r.URL.Path, "/config/")
dir := path.Dir(urlpath)
file := path.Base(urlpath)
2024-07-24 13:13:46 +09:00
sourceFile := path.Join(h.deployPath, dir, "config", file)
logger.Println("config dest :", sourceFile)
bt, err := os.ReadFile(sourceFile)
if err != nil && !os.IsExist(err) {
logger.Println("config file is missing :", sourceFile)
w.WriteHeader(http.StatusNotFound)
} else {
if _, err = w.Write(bt); err != nil {
logger.Println("config write failed :", err)
w.WriteHeader(http.StatusInternalServerError)
}
}
2024-06-05 13:41:43 +09:00
} else {
http.NotFound(w, r)
}
})
2023-05-23 13:54:25 +09:00
2023-06-13 11:04:30 +09:00
ufsx := http.FileServer(http.Dir(h.downloadPath))
2023-06-22 20:39:38 +09:00
serveMux.Handle(fmt.Sprintf("%s/%s/", prefix, sub_folder_name_downloads), http.StripPrefix(fmt.Sprintf("%s/%s/", prefix, sub_folder_name_downloads), ufsx))
2023-05-23 13:54:25 +09:00
2023-06-10 16:27:46 +09:00
serveMux.HandleFunc(fmt.Sprintf("%s/upload", prefix), func(w http.ResponseWriter, r *http.Request) {
2023-05-23 13:54:25 +09:00
defer func() {
s := recover()
if s != nil {
2024-09-26 12:01:53 +09:00
logger.Error(s)
2023-05-23 13:54:25 +09:00
}
io.Copy(io.Discard, r.Body)
r.Body.Close()
}()
name := r.Header.Get("Houston-Service-Name")
version := r.Header.Get("Houston-Service-Version")
filename := r.Header.Get("Houston-Service-Filename")
2023-06-13 11:04:30 +09:00
dir := path.Join(h.downloadPath, name, version)
if err := os.MkdirAll(dir, 0775); err == nil {
2024-09-26 13:18:32 +09:00
filepath := path.Join(dir, filename)
// filepath가 이미 있으면 append
localfile, _ := os.OpenFile(filepath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
2024-09-26 13:18:32 +09:00
logger.Println("file uploaded :", localfile)
if localfile != nil {
defer localfile.Close()
2024-09-26 13:18:32 +09:00
if _, err = io.Copy(localfile, r.Body); err != nil {
2023-05-23 13:54:25 +09:00
w.WriteHeader(http.StatusInternalServerError)
}
} else {
w.WriteHeader(http.StatusInternalServerError)
}
} else {
w.WriteHeader(http.StatusInternalServerError)
}
})
2023-05-22 00:54:49 +09:00
return nil
}
func (h *houstonHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() {
s := recover()
if s != nil {
2023-06-14 00:13:51 +09:00
logger.Println(s)
2023-05-22 00:54:49 +09:00
debug.PrintStack()
}
}()
defer func() {
io.Copy(io.Discard, r.Body)
r.Body.Close()
}()
2023-05-23 13:54:25 +09:00
var operation string
if r.Method == "POST" {
operation = r.FormValue("operation")
} else {
operation = r.URL.Query().Get("operation")
}
2023-05-22 00:54:49 +09:00
if len(operation) == 0 {
w.WriteHeader(http.StatusBadRequest)
return
}
method, ok := h.methods[strings.ToLower(operation)]
if !ok {
// 없는 operation
2023-06-14 00:13:51 +09:00
logger.Println("fail to call api. operation is not valid :", operation)
2023-05-22 00:54:49 +09:00
w.WriteHeader(http.StatusBadRequest)
return
}
args := []reflect.Value{
reflect.ValueOf(h),
reflect.ValueOf(w),
reflect.ValueOf(r),
}
2023-06-14 15:51:54 +09:00
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
2023-05-22 00:54:49 +09:00
method.Func.Call(args)
}