Browse Source

fix GoExtData以及完善网络请求

tags/v0.9.2
3136352472 5 years ago
parent
commit
4dd82b7d62
  1. 12
      govue/bindata.go
  2. 59
      govue/cmd/main.go
  3. 11
      govue/config.go
  4. 1286
      govue/govue-js-src/dist/index.js
  5. 1
      govue/govue-js-src/package.json
  6. 3
      govue/govue-js-src/predo.js
  7. 65
      govue/govue-js-src/src/goruntime.js
  8. 1286
      govue/govue-runtime/govue.js
  9. 66
      govue/govue-runtime/header.js
  10. 10
      govue/govue-runtime/runtime.js
  11. 39
      govue/govue.go
  12. 9
      jsruntime/cookie.go
  13. 152
      jsruntime/go_request.go
  14. 4
      jsruntime/runtime.go
  15. 4
      pool/pool.go
  16. 24
      static/404.html
  17. 3
      static/index.html
  18. 1
      static/use.js

12
govue/bindata.go
File diff suppressed because it is too large
View File

59
govue/cmd/main.go

@ -5,8 +5,10 @@ import (
"fmt"
"git.ouxuan.net/3136352472/go-service-template/govue"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"log"
"mime"
"net/http"
"path/filepath"
)
@ -17,6 +19,7 @@ func main() {
var useFile string
var mode string
var path string
var errorPage404 string
flag.StringVar(&path, "config", "govue.json", "配置文件路径")
@ -28,6 +31,8 @@ func main() {
flag.StringVar(&mode, "mode", "", "模式release/debug")
flag.StringVar(&errorPage404, "error_page_404", "", "404错误页面路径")
flag.Parse()
if flag.Arg(0) == "init" {
@ -65,19 +70,43 @@ func main() {
govue.SetPoolConfig(config.Pool)
gv, err := govue.NewGoVue(config.UseJsFile, config.StaticDir)
if errorPage404 != "" {
config.ErrorPage404 = errorPage404
}
gv.SetErrorPage404(config.ErrorPage404)
if err != nil {
panic(err)
}
r.NoRoute(func(context *gin.Context) {
raw, err := gv.LoadStaticResources(context.Request)
cookies := context.Request.Cookies()
extData := map[string]interface{}{
"cookie": map[string]string{},
}
for e := range cookies {
extData["cookie"].(map[string]string)[cookies[e].Name] = cookies[e].Value
}
if extData["cookie"].(map[string]string)["extdatasessionkey"] == "" {
context.SetCookie("extdatasessionkey", uuid.Must(uuid.NewUUID()).String(), 0, "", context.Request.Host, http.SameSiteLaxMode, false, false)
}
raw, err := gv.LoadStaticResources(context.Request, extData)
if err != nil {
_, _ = context.Writer.Write([]byte(fmt.Sprintln("服务器错误", err.Error())))
_, _ = context.Writer.Write(raw)
return
}
mime.TypeByExtension(filepath.Ext(context.Request.URL.Path))
context.Writer.Header().Set("Content-Type", mime.TypeByExtension(filepath.Ext(context.Request.URL.Path)))
ext := filepath.Ext(context.Request.URL.Path)
if ext == "" {
ext = ".html"
}
context.Writer.Header().Set("Content-Type", mime.TypeByExtension(ext)+"; charset=utf-8")
context.Writer.WriteHeader(200)
_, _ = context.Writer.Write(raw)
})
@ -88,6 +117,29 @@ func main() {
context.Header("Access-Control-Allow-Headers", "Action, Module, X-PINGOTHER, Content-Type, Content-Disposition")
})
//var GoExtDataMap map[string]map[string]interface{}
//r.GET("/GoExtData", func(context *gin.Context) {
// key, err := context.Cookie("extdatasessionkey")
// if err != nil {
// context.SetCookie("extdatasessionkey", uuid.Must(uuid.NewUUID()).String(), 0, "", context.Request.Host, http.SameSiteLaxMode, false, false)
// }
// var old = GoExtDataMap[key]
//
// var result map[string]interface{}
// data, _ := ioutil.ReadAll(context.Request.Body)
// _ = json.Unmarshal(data, &result)
//
// for e := range result {
// old[e] = result[e]
// }
// GoExtDataMap[key] = old
//
// context.JSON(200, map[string]interface{}{
// "code": 0,
// "data": GoExtDataMap[key],
// })
//})
r.GET("/version", func(context *gin.Context) {
context.JSON(200, map[string]interface{}{
"code": 0,
@ -98,7 +150,6 @@ func main() {
gv.StartPoolLog()
for {
err = r.Run(config.Addr)
if err != nil {
log.Println("服务意外停止:", err)

11
govue/config.go

@ -6,11 +6,12 @@ import (
)
type Config struct {
Addr string `json:"addr"`
StaticDir string `json:"static_dir"`
UseJsFile string `json:"use_js_file"`
Mode string `json:"mode"`
Pool pool.Config `json:"pool"`
Addr string `json:"addr"`
StaticDir string `json:"static_dir"`
UseJsFile string `json:"use_js_file"`
ErrorPage404 string `json:"error_page_404"`
Mode string `json:"mode"`
Pool pool.Config `json:"pool"`
}
func GenerateConfig(path string) (err error) {

1286
govue/govue-js-src/dist/index.js
File diff suppressed because it is too large
View File

1
govue/govue-js-src/package.json

@ -2,7 +2,6 @@
"name": "govue-template",
"dependencies": {
"axios": "^0.19.2",
"axios-miniprogram-adapter": "^0.3.0",
"domino": "^2.1.5",
"envify": "^4.1.0",
"es6-promise": "^4.2.8",

3
govue/govue-js-src/predo.js

@ -5,8 +5,11 @@ var retemp2 = fs.readFileSync("./replace2.tp")
var content = fs.readFileSync("./dist/index.js")
retemp = retemp.toString().replace(/\r\n/g,"\n")
var test = content.toString().indexOf(retemp)
console.log(test)
content = content.toString().replace(retemp, `NodeList`).replace(retemp2, ``)
fs.writeFileSync("./dist/index.js", content)

65
govue/govue-js-src/src/goruntime.js

@ -5,13 +5,68 @@ location = window.location;
Promise = require('es6-promise').Promise;
Vue = require('vue');
Vue = require('vue');
$ = jQuery = require('jquery');
require('jquery-bbq');
qs = require('qs');
axios = require('axios');
import mpAdapter from 'axios-miniprogram-adapter'
axios.defaults.adapter = mpAdapter
var buildURL = require('axios/lib/helpers/buildURL');
var buildFullPath = require('axios/lib/core/buildFullPath');
var settle = require('axios/lib/core/settle');
var createError = require('axios/lib/core/createError');
function transformResponse(mpResponse, config, mpRequestOption) {
var headers = mpResponse.header || mpResponse.headers;
var status = mpResponse.statusCode || mpResponse.status;
var statusText = '';
if (status === 200) {
statusText = 'OK';
}
else if (status === 400) {
statusText = 'Bad Request';
}
var response = {
data: mpResponse.data,
status: status,
statusText: statusText,
headers: headers,
config: config,
request: mpRequestOption
};
return response;
}
axios.defaults.adapter = function (config) {
return new Promise(function (resolve, reject) {
console.log("resolve", JSON.stringify(resolve));
console.log("reject", JSON.stringify(reject));
console.log("config", JSON.stringify(config));
console.log("axios.defaults.headers", JSON.stringify(axios.defaults.headers));
var mpRequestOption = {
url: buildURL(buildFullPath(config.baseURL, config.url), config.params, config.paramsSerializer),
method: config["method"].toUpperCase(),
data: config["data"],
header: config["headers"],
timeout: config["timeout"],
success: function (mpResponse) {
console.log("success");
console.log(JSON.stringify(mpResponse));
var response = transformResponse(mpResponse, config, mpRequestOption);
settle(resolve, reject, response);
},
fail: function (error) {
reject(createError(error.data));
},
};
net.request(mpRequestOption)
})
};
useRoute = {};
@ -30,7 +85,7 @@ GoUseCall = function (e) {
// console.log("GoUseCall", 2)
var id = e["id"];
var path = e["path"];
if(!e["query"]){
if (!e["query"]) {
console.log("query未找到");
e["query"] = {};
}

1286
govue/govue-runtime/govue.js
File diff suppressed because it is too large
View File

66
govue/govue-runtime/header.js

@ -1,22 +1,22 @@
var domino, window, document, location, Vue, VueRouter, navigator, axios, Promise, GoUseCall, GoUse, GoUseRegistered,
govueId, useRoute, goUseCallCache, $, jQuery, GoParam;
govueId, useRoute, goUseCallCache, $, jQuery, GoParam, qs;
navigator = {
userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"
};
var wx = {
var net = {
request: function (c) {
var url = c["url"];
var data = c["data"];
var header = c["header"];
var method = c["method"];
var dataType = c["dataType"];
var responseType = c["responseType"];
var timeout = c["timeout"];
var success = c["success"];
var fail = c["fail"];
var complete = c["complete"];
// console.log("request");
// console.log(url);
var isHost = url.indexOf("http://") > -1 || url.indexOf("https://") > -1;
var isAbs = (url[0] == '/');
if (!isHost) {
@ -31,29 +31,60 @@ var wx = {
url = location.protocol + "//" + url
}
// console.log("url",url);
var result = GoRequest({
if (data) {
if (method == "GET") {
url = $.param.querystring(url, data);
data = ""
} else {
console.log("data:");
console.log(JSON.stringify(header["Content-Type"]));
console.log(JSON.stringify(data));
if (typeof (data) == "object") {
if (header["Content-Type"].indexOf("application/json") > -1 || header["content-type"].indexOf("application/json") > -1) {
data = JSON.stringify(data);
} else {
data = $.param(data);
}
}
}
}
var resp = GoRequest({
url: url,
data: data,
method: method,
header: header,
timeout: timeout
});
result = JSON.parse(result);
var statusCode = result["statusCode"];
var data = result["data"];
resp = JSON.parse(resp);
var statusCode = resp["statusCode"];
var result = resp["data"];
if (dataType == "json") {
data = JSON.parse(data)
result = JSON.parse(result)
}
success({
data: data,
statusCode: statusCode,
});
if (statusCode == 200) {
success({
data: result,
statusCode: statusCode,
});
} else {
fail({
data: result,
statusCode: statusCode,
})
}
}
};
/**
* 获取页面Id
* @return {string}
@ -88,10 +119,10 @@ function RunInlineCode() {
jsInlineFiles.unshift(res);
}
if (isGoVueCommon){
if (isGoVueCommon) {
jsInline[i].removeAttribute("gv-src");
jsInline[i].removeAttribute("gv-common");
}else{
} else {
jsInline[i].remove();
}
}
@ -126,7 +157,6 @@ var GoVueIgnore = function () {
var gv_ignore_class_len = 0;
/**
* 忽略前置
*/

10
govue/govue-runtime/runtime.js

@ -1,11 +1,13 @@
window = domino.createWindow(GoHtmlSrc, GoHref);
document = window.document;
location = window.location;
location = window.location;
try {
var govueId = GetGoVueId();
LoadGoParam();
@ -14,14 +16,14 @@ try {
goVueIgnore.ignore();
RunInlineCode();
//
GoUseCall({
id: govueId,
path: GoPath,
query: jQuery.deparam(GoQuery)
});
//
//
goVueIgnore.restore()

39
govue/govue.go

@ -18,6 +18,7 @@ import (
type GoVue struct {
StaticPath string
UseJsPath string
ErrorPage404 string
Resources *assetfs.AssetFS
jsRuntimePool *pool.JsRuntimePool
}
@ -41,6 +42,10 @@ func NewGoVue(useJsPath string, staticPath string) (gv *GoVue, err error) {
return
}
func (gv *GoVue) SetErrorPage404(page string) {
gv.ErrorPage404 = page
}
func SetPoolConfig(config pool.Config) {
pool.DefaultConfig = config
}
@ -62,7 +67,7 @@ func (gv *GoVue) initRender() (err error) {
//if err != nil {
// return
//}
//govueScript, err := ioutil.ReadFile(filepath.Join("govue-js-src", "dist", "index.js"))
//govueScript, err := ioutil.ReadFile(filepath.Join("govue", "govue-js-src", "dist", "index.js"))
//if err != nil {
// return
//}
@ -117,7 +122,7 @@ func (gv *GoVue) StartPoolLog() {
}()
}
func (gv *GoVue) LoadStaticResources(request *http.Request) (result []byte, err error) {
func (gv *GoVue) LoadStaticResources(request *http.Request, goExtDataS ...interface{}) (result []byte, err error) {
var path string
var staticDir string
var filePath = request.URL.Path
@ -131,7 +136,7 @@ func (gv *GoVue) LoadStaticResources(request *http.Request) (result []byte, err
fi, err := os.Stat(path)
if err != nil {
return
return gv.renderErrPage(404, request, goExtDataS...)
} else if fi.IsDir() {
filePath = filepath.Join(filePath, "index.html")
path = filepath.Join(staticDir, filePath)
@ -139,14 +144,38 @@ func (gv *GoVue) LoadStaticResources(request *http.Request) (result []byte, err
result, err = ioutil.ReadFile(path)
if !pathExists(path) || err != nil {
return
return gv.renderErrPage(404, request, goExtDataS...)
}
if filepath.Ext(path) != ".html" {
return
}
var goExtData interface{}
if len(goExtDataS) > 0 {
goExtData = goExtDataS[0]
}
err = gv.jsRuntimePool.JsRuntimeCall(func(jr *jsruntime.JsRuntime) {
err = jr.Render(filePath, fmt.Sprintf("http://%s%s", request.Host, request.RequestURI), string(result), goExtData, func(data string) {
result = []byte(data)
})
})
return
}
func (gv *GoVue) renderErrPage(errCode int, request *http.Request, goExtDataS ...interface{}) (result []byte, err error) {
filePath := gv.ErrorPage404
if filePath == "" {
return []byte("页面不存在"), err
}
result, _ = ioutil.ReadFile(filePath)
var goExtData interface{}
if len(goExtDataS) > 0 {
goExtData = goExtDataS[0]
}
err = gv.jsRuntimePool.JsRuntimeCall(func(jr *jsruntime.JsRuntime) {
err = jr.Render(filePath, fmt.Sprintf("http://%s%s", request.Host, request.RequestURI), string(result), func(data string) {
err = jr.Render(filePath, fmt.Sprintf("http://%s%s", request.Host, request.RequestURI), string(result), goExtData, func(data string) {
result = []byte(data)
})
})

9
jsruntime/cookie.go

@ -0,0 +1,9 @@
package jsruntime
import "log"
func (jr *JsRuntime) EnableCookieFun() {
jr.runtime.Set("setInterval", func() {
log.Println("禁用setInterval")
})
}

152
jsruntime/go_request.go

@ -1,50 +1,146 @@
package jsruntime
import (
"bytes"
"encoding/json"
"git.ouxuan.net/hasaki-service/hasaki-sdk/hskhttpdo"
"github.com/parnurzeal/gorequest"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
func (jr *JsRuntime) EnableRequestFunc() {
jr.runtime.Set("GoRequest", func(call map[string]interface{}) (statusCode int, respData string) {
jr.runtime.Set("GoRequest", func(call map[string]interface{}) (respData string) {
url := call["url"].(string)
data := call["data"]
header := call["header"].(map[string]string)
//timeout := call.Argument(3)
method := call["method"].(string)
//dataType := call["dataType"]
//responseType := call["responseType"]
url := ""
if call["url"] != nil {
url = call["url"].(string)
}
data := ""
if call["data"] != nil {
data = call["data"].(string)
}
header := map[string]interface{}{}
if call["header"] != nil {
header = call["header"].(map[string]interface{})
}
//log.Println("url.String()", url)
//log.Println("data.String()", data)
timeout := 0
if call["timeout"] != nil {
switch call["timeout"].(type) {
case int64:
timeout = int(call["timeout"].(int64))
case int:
timeout = call["timeout"].(int)
}
}
client := &http.Client{}
method := "GET"
if call["method"] != nil {
method = call["method"].(string)
}
req, err := http.NewRequest("GET", url, nil)
client := &http.Client{
Timeout: time.Millisecond * time.Duration(timeout),
}
var contentReader *bytes.Reader
contentReader = bytes.NewReader([]byte(data))
//log.Println(method, url, data)
req, err := http.NewRequest(method, url, contentReader)
if err != nil {
rs, _ := json.Marshal(map[string]interface{}{
"statusCode": 504,
"data": err.Error(),
})
return string(rs)
}
for e := range header {
req.Header.Add(e, header[e])
req.Header.Set(e, header[e].(string))
}
resp, err := client.Do(req)
statusCode = resp.StatusCode
gorequest.New().Header.
res, err := hskhttpdo.HttpDo{
Url: url,
Raw: []byte(data),
}.Request(method)
var statusCode int
var respDatas string
r := map[string]interface{}{
"statusCode": 200,
"data": string(res),
}
if err != nil {
r["code"] = 502
if err == nil {
defer resp.Body.Close()
statusCode = resp.StatusCode
rb, _ := ioutil.ReadAll(resp.Body)
respDatas = string(rb)
} else {
statusCode = 502
respDatas = err.Error()
}
rs, _ := json.Marshal(r)
log2File("netword", "-------------------------------------------------")
log2File("netword", "网络请求:", method, url)
headerStr, _ := json.Marshal(header)
log2File("netword", "网络请求头:", string(headerStr))
log2File("netword", "网络请求发送数据:", data)
log2File("netword", "请求返回状态:", err == nil)
log2File("netword", "请求返回状态码:", statusCode)
log2File("netword", "请求返回:", respDatas)
log2File("netword", "-------------------------------------------------")
rs, _ := json.Marshal(map[string]interface{}{
"statusCode": statusCode,
"data": string(respDatas),
})
return string(rs)
})
}
func log2File(tag string, strs ...interface{}) {
str := fmt.Sprintln(strs...)
path := filepath.Join(getSelfFilePath(), fmt.Sprintf("jsruntime-%s.log", tag))
if pathExists(path) {
raw, _ := ioutil.ReadFile(path)
str = string(raw) + str
}
ioutil.WriteFile(path, []byte(str), 0644)
}
func pathExists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return false
}
var selfFilePath string
func getSelfFilePath() string {
if selfFilePath == "" {
file, err := exec.LookPath(os.Args[0])
if err != nil {
return ""
}
path, err := filepath.Abs(file)
if err != nil {
return ""
}
i := strings.LastIndex(path, "/")
if i < 0 {
i = strings.LastIndex(path, "\\")
}
if i < 0 {
return ""
}
selfFilePath, _ = filepath.Abs(string(path[0 : i+1]))
}
return selfFilePath
}

4
jsruntime/runtime.go

@ -119,7 +119,7 @@ func (jr *JsRuntime) RunCode(code string) error {
return err
}
func (jr *JsRuntime) Render(filePath, href, tplSrc string, cb func(data string)) (err error) {
func (jr *JsRuntime) Render(filePath, href, tplSrc string, GoExtData interface{}, cb func(data string)) (err error) {
jr.mutex.Lock()
defer jr.mutex.Unlock()
@ -154,6 +154,8 @@ func (jr *JsRuntime) Render(filePath, href, tplSrc string, cb func(data string))
return errors.New(err.Error() + "3")
}
runtime.Set("GoExtData", GoExtData)
runtime.Set("GoHtmlSrc", tplSrc)
runtime.Set("GoHref", href)

4
pool/pool.go

@ -10,7 +10,8 @@ import (
)
type JsRuntimePool struct {
ctx context.Context
ctx context.Context
jsRuntimePool *pool.ObjectPool
}
type Config struct {
@ -29,6 +30,7 @@ func NewJsRuntimePool(mainScript string, useFileName string, staticPath string,
factory := pool.NewPooledObjectFactorySimple(
func(context.Context) (interface{}, error) {
render, err := jsruntime.NewJsRuntime(mainScript, staticPath, relys, mode)
render.UseSrcFun = func() string {
return useSrc
}

24
static/404.html

@ -0,0 +1,24 @@
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="keywords" content="">
<link rel="stylesheet" href="css/main.css">
<script src="js/vue.min.js"></script>
</head>
<body>
<div id="app" class="content">
<my-title></my-title>
<a>404 找不到页面 {{desc}}</a>
</div>
</body>
<script gv-src>
new Vue({
el: "#app",
data: {
"desc": "基础golang开发的一套vue服务端渲染方案"
},
});
</script>
</html>

3
static/index.html

@ -23,6 +23,9 @@
</body>
<script src="index.js" gv-src></script>
<script gv-src gv-common>
console.log("GoExtData",JSON.stringify(GoExtData))
new Vue({
el: "#quick_start",
data: {

1
static/use.js

@ -4,6 +4,7 @@ GoUse(function () {
// 定义一个名为 button-counter 的新组件
document.title = "govue";
document
.getElementsByName("keywords")[0]
.setAttribute("content", "govue,服务端渲染,ssr");

Loading…
Cancel
Save