/* * Micro Service * Package: gitlab.hexacode.org/go-libs/microservice * Maintainer: Azzis Arswendo * * Copyright (C) 2023 Hexacode Teknologi Indonesia * All Rights Reserved */ package config import ( "net/http" "strconv" "github.com/gin-gonic/gin" "gitlab.hexacode.org/go-libs/hctypes" "gitlab.hexacode.org/go-libs/microservice/validate" ) type ConfigTemplateContext struct { Url string `json:"url,omitempty"` Config *Config `json:"config,omitempty"` ConfigTemplate *ConfigTemplate `json:"config_template,omitempty"` URLParams hctypes.Dict `json:"url_params,omitempty"` Headers hctypes.Dict `json:"headers,omitempty"` Request *http.Request `json:"-"` Writer http.ResponseWriter `json:"-"` } type ConfigTemplate struct { Name string `json:"name,omitempty"` Path string `json:"path,omitempty"` FilePath string `json:"file_path,omitempty"` Callback *ConfigTemplateCallback `json:"callback,omitempty"` URLParams []*validate.Options `json:"url_params,omitempty"` config *Config `json:"-"` } func (config_template *ConfigTemplate) HTTPHandler(ctx *gin.Context) { url_params := hctypes.Dict{} headers := hctypes.Dict{} raw_headers := ctx.Request.Header.Clone() for k, v := range raw_headers { headers[k] = hctypes.String(v[0]) } for _, param := range ctx.Params { url_params[param.Key] = hctypes.String(param.Value) } ret := config_template.Callback.function(&ConfigTemplateContext{ Url: ctx.Request.URL.Path, Config: config_template.config, ConfigTemplate: config_template, URLParams: url_params, Headers: headers, Request: ctx.Request, Writer: ctx.Writer, }) meta := "null" if ret != nil { meta = string(ret.ToJson()) } template, err := NewTemplateFromFile(config_template.FilePath) if err != nil { ctx.String(http.StatusInternalServerError, "500 Internal Server Error") return } render, err := template.Render(hctypes.Dict{ "meta": hctypes.String(meta), }) if err != nil { ctx.String(http.StatusInternalServerError, "500 Internal Server Error") return } ctx.Writer.WriteHeader(http.StatusOK) ctx.Writer.Header().Set("Content-Type", "text/html; charset=utf-8") ctx.Writer.Header().Set("Content-Length", strconv.Itoa(len(render))) ctx.Writer.WriteHeaderNow() ctx.Writer.Write([]byte(render)) }