Best K6 code snippet using html.Exports
generator.go
Source:generator.go
1package genjs2import (3 "flag"4 "fmt"5 "os"6 "path/filepath"7 "sort"8 "strings"9 "text/template"10 "time"11 "github.com/shogo82148/goa-v1/design"12 "github.com/shogo82148/goa-v1/goagen/codegen"13 "github.com/shogo82148/goa-v1/goagen/utils"14)15//NewGenerator returns an initialized instance of a JavaScript Client Generator16func NewGenerator(options ...Option) *Generator {17 g := &Generator{}18 for _, option := range options {19 option(g)20 }21 return g22}23// Generator is the application code generator.24type Generator struct {25 API *design.APIDefinition // The API definition26 OutDir string // Destination directory27 Timeout time.Duration // Timeout used by JavaScript client when making requests28 Scheme string // Scheme used by JavaScript client29 Host string // Host addressed by JavaScript client30 NoExample bool // Do not generate an HTML example file31 genfiles []string // Generated files32}33// Generate is the generator entry point called by the meta generator.34func Generate() (files []string, err error) {35 var (36 outDir, ver string37 timeout time.Duration38 scheme, host string39 noexample bool40 )41 set := flag.NewFlagSet("client", flag.PanicOnError)42 set.StringVar(&outDir, "out", "", "")43 set.String("design", "", "")44 set.DurationVar(&timeout, "timeout", time.Duration(20)*time.Second, "")45 set.StringVar(&scheme, "scheme", "", "")46 set.StringVar(&host, "host", "", "")47 set.StringVar(&ver, "version", "", "")48 set.BoolVar(&noexample, "noexample", false, "")49 set.Parse(os.Args[1:])50 // First check compatibility51 if err := codegen.CheckVersion(ver); err != nil {52 return nil, err53 }54 // Now proceed55 g := &Generator{OutDir: outDir, Timeout: timeout, Scheme: scheme, Host: host, NoExample: noexample, API: design.Design}56 return g.Generate()57}58// Generate produces the skeleton main.59func (g *Generator) Generate() (_ []string, err error) {60 if g.API == nil {61 return nil, fmt.Errorf("missing API definition, make sure design is properly initialized")62 }63 go utils.Catch(nil, func() { g.Cleanup() })64 defer func() {65 if err != nil {66 g.Cleanup()67 }68 }()69 if g.Timeout == 0 {70 g.Timeout = 20 * time.Second71 }72 if g.Scheme == "" && len(g.API.Schemes) > 0 {73 g.Scheme = g.API.Schemes[0]74 }75 if g.Scheme == "" {76 g.Scheme = "http"77 }78 if g.Host == "" {79 g.Host = g.API.Host80 }81 if g.Host == "" {82 return nil, fmt.Errorf("missing host value, set it with --host")83 }84 g.OutDir = filepath.Join(g.OutDir, "js")85 if err := os.RemoveAll(g.OutDir); err != nil {86 return nil, err87 }88 if err := os.MkdirAll(g.OutDir, 0755); err != nil {89 return nil, err90 }91 g.genfiles = append(g.genfiles, g.OutDir)92 // Generate client.js93 exampleAction, err := g.generateJS(filepath.Join(g.OutDir, "client.js"))94 if err != nil {95 return96 }97 // Generate axios.html98 if err = g.generateAxiosJS(); err != nil {99 return100 }101 if exampleAction != nil && !g.NoExample {102 // Generate index.html103 if err = g.generateIndexHTML(filepath.Join(g.OutDir, "index.html"), exampleAction); err != nil {104 return105 }106 // Generate example107 if err = g.generateExample(); err != nil {108 return109 }110 }111 return g.genfiles, nil112}113func (g *Generator) generateJS(jsFile string) (_ *design.ActionDefinition, err error) {114 file, err := codegen.SourceFileFor(jsFile)115 if err != nil {116 return117 }118 defer file.Close()119 g.genfiles = append(g.genfiles, jsFile)120 data := map[string]interface{}{121 "API": g.API,122 "Host": g.Host,123 "Scheme": g.Scheme,124 "Timeout": int64(g.Timeout / time.Millisecond),125 }126 if err = file.ExecuteTemplate("module", moduleT, nil, data); err != nil {127 return128 }129 actions := make(map[string][]*design.ActionDefinition)130 g.API.IterateResources(func(res *design.ResourceDefinition) error {131 return res.IterateActions(func(action *design.ActionDefinition) error {132 if as, ok := actions[action.Name]; ok {133 actions[action.Name] = append(as, action)134 } else {135 actions[action.Name] = []*design.ActionDefinition{action}136 }137 return nil138 })139 })140 var exampleAction *design.ActionDefinition141 keys := []string{}142 for n := range actions {143 keys = append(keys, n)144 }145 sort.Strings(keys)146 for _, n := range keys {147 for _, a := range actions[n] {148 if exampleAction == nil && a.Routes[0].Verb == "GET" {149 exampleAction = a150 }151 data := map[string]interface{}{"Action": a}152 funcs := template.FuncMap{"params": params}153 if err = file.ExecuteTemplate("jsFuncs", jsFuncsT, funcs, data); err != nil {154 return155 }156 }157 }158 _, err = file.Write([]byte(moduleTend))159 return exampleAction, err160}161func (g *Generator) generateIndexHTML(htmlFile string, exampleAction *design.ActionDefinition) error {162 file, err := codegen.SourceFileFor(htmlFile)163 if err != nil {164 return err165 }166 defer file.Close()167 g.genfiles = append(g.genfiles, htmlFile)168 argNames := params(exampleAction)169 var args string170 if len(argNames) > 0 {171 query := exampleAction.QueryParams.Type.ToObject()172 argValues := make([]string, len(argNames))173 for i, n := range argNames {174 ex := query[n].GenerateExample(g.API.RandomGenerator(), nil)175 argValues[i] = fmt.Sprintf("%v", ex)176 }177 args = strings.Join(argValues, ", ")178 }179 examplePath := exampleAction.Routes[0].FullPath()180 pathParams := exampleAction.Routes[0].Params()181 if len(pathParams) > 0 {182 pathVars := exampleAction.AllParams().Type.ToObject()183 pathValues := make([]interface{}, len(pathParams))184 for i, n := range pathParams {185 ex := pathVars[n].GenerateExample(g.API.RandomGenerator(), nil)186 pathValues[i] = ex187 }188 format := design.WildcardRegex.ReplaceAllLiteralString(examplePath, "/%v")189 examplePath = fmt.Sprintf(format, pathValues...)190 }191 if len(argNames) > 0 {192 args = ", " + args193 }194 exampleFunc := fmt.Sprintf(195 `%s%s ("%s"%s)`,196 exampleAction.Name,197 strings.Title(exampleAction.Parent.Name),198 examplePath,199 args,200 )201 data := map[string]interface{}{202 "API": g.API,203 "ExampleFunc": exampleFunc,204 }205 return file.ExecuteTemplate("exampleHTML", exampleT, nil, data)206}207func (g *Generator) generateAxiosJS() error {208 filePath := filepath.Join(g.OutDir, "axios.min.js")209 if err := os.WriteFile(filePath, []byte(axios), 0644); err != nil {210 return err211 }212 g.genfiles = append(g.genfiles, filePath)213 return nil214}215func (g *Generator) generateExample() error {216 controllerFile := filepath.Join(g.OutDir, "example.go")217 file, err := codegen.SourceFileFor(controllerFile)218 if err != nil {219 return err220 }221 defer func() {222 file.Close()223 if err == nil {224 err = file.FormatCode()225 }226 }()227 imports := []*codegen.ImportSpec{228 codegen.SimpleImport("net/http"),229 codegen.SimpleImport("github.com/dimfeld/httptreemux"),230 codegen.NewImport("goa", "github.com/shogo82148/goa-v1"),231 }232 if err := file.WriteHeader(fmt.Sprintf("%s JavaScript Client Example", g.API.Name), "js", imports); err != nil {233 return err234 }235 g.genfiles = append(g.genfiles, controllerFile)236 data := map[string]interface{}{"ServeDir": g.OutDir}237 return file.ExecuteTemplate("examples", exampleCtrlT, nil, data)238}239// Cleanup removes all the files generated by this generator during the last invokation of Generate.240func (g *Generator) Cleanup() {241 for _, f := range g.genfiles {242 os.Remove(f)243 }244 g.genfiles = nil245}246func params(action *design.ActionDefinition) []string {247 if action.QueryParams == nil {248 return nil249 }250 params := make([]string, len(action.QueryParams.Type.ToObject()))251 i := 0252 for n := range action.QueryParams.Type.ToObject() {253 params[i] = n254 i++255 }256 sort.Strings(params)257 return params258}259const moduleT = `// This module exports functions that give access to the {{.API.Name}} API hosted at {{.API.Host}}.260// It uses the axios javascript library for making the actual HTTP requests.261define(['axios'] , function (axios) {262 function merge(obj1, obj2) {263 var obj3 = {};264 for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }265 for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }266 return obj3;267 }268 return function (scheme, host, timeout) {269 scheme = scheme || '{{.Scheme}}';270 host = host || '{{.Host}}';271 timeout = timeout || {{.Timeout}};272 // Client is the object returned by this module.273 var client = axios;274 // URL prefix for all API requests.275 var urlPrefix = scheme + '://' + host;276`277const moduleTend = ` return client;278 };279});280`281const jsFuncsT = `{{$params := params .Action}}282 {{$name := printf "%s%s" .Action.Name (title .Action.Parent.Name)}}// {{if .Action.Description}}{{.Action.Description}}{{else}}{{$name}} calls the {{.Action.Name}} action of the {{.Action.Parent.Name}} resource.{{end}}283 // path is the request path, the format is "{{(index .Action.Routes 0).FullPath}}"284 {{if .Action.Payload}}// data contains the action payload (request body)285 {{end}}{{if $params}}// {{join $params ", "}} {{if gt (len $params) 1}}are{{else}}is{{end}} used to build the request query string.286 {{end}}// config is an optional object to be merged into the config built by the function prior to making the request.287 // The content of the config object is described here: https://github.com/mzabriskie/axios#request-api288 // This function returns a promise which raises an error if the HTTP response is a 4xx or 5xx.289 client.{{$name}} = function (path{{if .Action.Payload}}, data{{end}}{{if $params}}, {{join $params ", "}}{{end}}, config) {290 var cfg = {291 timeout: timeout,292 url: urlPrefix + path,293 method: '{{toLower (index .Action.Routes 0).Verb}}',294{{if $params}} params: {295{{range $index, $param := $params}}{{if $index}},296{{end}} {{$param}}: {{$param}}{{end}}297 },298{{end}}{{if .Action.Payload}} data: data,299{{end}} responseType: 'json'300 };301 if (config) {302 cfg = merge(cfg, config);303 }304 return client(cfg);305 }306`307const exampleT = `<!doctype html>308<html>309 <head>310 <title>goa JavaScript client loader</title>311 </head>312 <body>313 <h1>{{.API.Name}} Client Test</h1>314 <div id="response"></div>315 <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.16/require.min.js"></script>316 <script>317 requirejs.config({318 paths: {319 axios: '/js/axios.min',320 client: '/js/client'321 }322 });323 requirejs(['client'], function (client) {324 client().{{.ExampleFunc}}325 .then(function (resp) {326 document.getElementById('response').innerHTML = resp.statusText;327 })328 .catch(function (resp) {329 document.getElementById('response').innerHTML = resp.statusText;330 });331 });332 </script>333 </body>334</html>335`336const exampleCtrlT = `// MountController mounts the JavaScript example controller under "/js".337// This is just an example, not the best way to do this. A better way would be to specify a file338// server using the Files DSL in the design.339// Use --noexample to prevent this file from being generated.340func MountController(service *goa.Service) {341 // Serve static files under js342 service.ServeFiles("/js/*filepath", {{printf "%q" .ServeDir}})343 service.LogInfo("mount", "ctrl", "JS", "action", "ServeFiles", "route", "GET /js/*")344}345`346const axios = `/* axios v0.7.0 | (c) 2015 by Matt Zabriskie */347!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.axios=t():e.axios=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){e.exports=n(1)},function(e,t,n){"use strict";var r=n(2),o=n(3),i=n(4),s=n(12),u=e.exports=function(e){"string"==typeof e&&(e=o.merge({url:arguments[0]},arguments[1])),e=o.merge({method:"get",headers:{},timeout:r.timeout,transformRequest:r.transformRequest,transformResponse:r.transformResponse},e),e.withCredentials=e.withCredentials||r.withCredentials;var t=[i,void 0],n=Promise.resolve(e);for(u.interceptors.request.forEach(function(e){t.unshift(e.fulfilled,e.rejected)}),u.interceptors.response.forEach(function(e){t.push(e.fulfilled,e.rejected)});t.length;)n=n.then(t.shift(),t.shift());return n};u.defaults=r,u.all=function(e){return Promise.all(e)},u.spread=n(13),u.interceptors={request:new s,response:new s},function(){function e(){o.forEach(arguments,function(e){u[e]=function(t,n){return u(o.merge(n||{},{method:e,url:t}))}})}function t(){o.forEach(arguments,function(e){u[e]=function(t,n,r){return u(o.merge(r||{},{method:e,url:t,data:n}))}})}e("delete","get","head"),t("post","put","patch")}()},function(e,t,n){"use strict";var r=n(3),o=/^\)\]\}',?\n/,i={"Content-Type":"application/x-www-form-urlencoded"};e.exports={transformRequest:[function(e,t){return r.isFormData(e)?e:r.isArrayBuffer(e)?e:r.isArrayBufferView(e)?e.buffer:!r.isObject(e)||r.isFile(e)||r.isBlob(e)?e:(r.isUndefined(t)||(r.forEach(t,function(e,n){"content-type"===n.toLowerCase()&&(t["Content-Type"]=e)}),r.isUndefined(t["Content-Type"])&&(t["Content-Type"]="application/json")),JSON.stringify(e))}],transformResponse:[function(e){if("string"==typeof e){e=e.replace(o,"");try{e=JSON.parse(e)}catch(t){}}return e}],headers:{common:{Accept:"application/json, text/plain, */*"},patch:r.merge(i),post:r.merge(i),put:r.merge(i)},timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN"}},function(e,t){"use strict";function n(e){return"[object Array]"===v.call(e)}function r(e){return"[object ArrayBuffer]"===v.call(e)}function o(e){return"[object FormData]"===v.call(e)}function i(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer}function s(e){return"string"==typeof e}function u(e){return"number"==typeof e}function a(e){return"undefined"==typeof e}function f(e){return null!==e&&"object"==typeof e}function c(e){return"[object Date]"===v.call(e)}function p(e){return"[object File]"===v.call(e)}function l(e){return"[object Blob]"===v.call(e)}function d(e){return e.replace(/^\s*/,"").replace(/\s*$/,"")}function h(e){return"[object Arguments]"===v.call(e)}function m(){return"undefined"!=typeof window&&"undefined"!=typeof document&&"function"==typeof document.createElement}function y(e,t){if(null!==e&&"undefined"!=typeof e){var r=n(e)||h(e);if("object"==typeof e||r||(e=[e]),r)for(var o=0,i=e.length;i>o;o++)t.call(null,e[o],o,e);else for(var s in e)e.hasOwnProperty(s)&&t.call(null,e[s],s,e)}}function g(){var e={};return y(arguments,function(t){y(t,function(t,n){e[n]=t})}),e}var v=Object.prototype.toString;e.exports={isArray:n,isArrayBuffer:r,isFormData:o,isArrayBufferView:i,isString:s,isNumber:u,isObject:f,isUndefined:a,isDate:c,isFile:p,isBlob:l,isStandardBrowserEnv:m,forEach:y,merge:g,trim:d}},function(e,t,n){(function(t){"use strict";e.exports=function(e){return new Promise(function(r,o){try{"undefined"!=typeof XMLHttpRequest||"undefined"!=typeof ActiveXObject?n(6)(r,o,e):"undefined"!=typeof t&&n(6)(r,o,e)}catch(i){o(i)}})}}).call(t,n(5))},function(e,t){function n(){f=!1,s.length?a=s.concat(a):c=-1,a.length&&r()}function r(){if(!f){var e=setTimeout(n);f=!0;for(var t=a.length;t;){for(s=a,a=[];++c<t;)s&&s[c].run();c=-1,t=a.length}s=null,f=!1,clearTimeout(e)}}function o(e,t){this.fun=e,this.array=t}function i(){}var s,u=e.exports={},a=[],f=!1,c=-1;u.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];a.push(new o(e,t)),1!==a.length||f||setTimeout(r,0)},o.prototype.run=function(){this.fun.apply(null,this.array)},u.title="browser",u.browser=!0,u.env={},u.argv=[],u.version="",u.versions={},u.on=i,u.addListener=i,u.once=i,u.off=i,u.removeListener=i,u.removeAllListeners=i,u.emit=i,u.binding=function(e){throw new Error("process.binding is not supported")},u.cwd=function(){return"/"},u.chdir=function(e){throw new Error("process.chdir is not supported")},u.umask=function(){return 0}},function(e,t,n){"use strict";var r=n(2),o=n(3),i=n(7),s=n(8),u=n(9);e.exports=function(e,t,a){var f=u(a.data,a.headers,a.transformRequest),c=o.merge(r.headers.common,r.headers[a.method]||{},a.headers||{});o.isFormData(f)&&delete c["Content-Type"];var p=new(XMLHttpRequest||ActiveXObject)("Microsoft.XMLHTTP");if(p.open(a.method.toUpperCase(),i(a.url,a.params),!0),p.timeout=a.timeout,p.onreadystatechange=function(){if(p&&4===p.readyState){var n=s(p.getAllResponseHeaders()),r=-1!==["text",""].indexOf(a.responseType||"")?p.responseText:p.response,o={data:u(r,n,a.transformResponse),status:p.status,statusText:p.statusText,headers:n,config:a};(p.status>=200&&p.status<300?e:t)(o),p=null}},o.isStandardBrowserEnv()){var l=n(10),d=n(11),h=d(a.url)?l.read(a.xsrfCookieName||r.xsrfCookieName):void 0;h&&(c[a.xsrfHeaderName||r.xsrfHeaderName]=h)}if(o.forEach(c,function(e,t){f||"content-type"!==t.toLowerCase()?p.setRequestHeader(t,e):delete c[t]}),a.withCredentials&&(p.withCredentials=!0),a.responseType)try{p.responseType=a.responseType}catch(m){if("json"!==p.responseType)throw m}o.isArrayBuffer(f)&&(f=new DataView(f)),p.send(f)}},function(e,t,n){"use strict";function r(e){return encodeURIComponent(e).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var o=n(3);e.exports=function(e,t){if(!t)return e;var n=[];return o.forEach(t,function(e,t){null!==e&&"undefined"!=typeof e&&(o.isArray(e)&&(t+="[]"),o.isArray(e)||(e=[e]),o.forEach(e,function(e){o.isDate(e)?e=e.toISOString():o.isObject(e)&&(e=JSON.stringify(e)),n.push(r(t)+"="+r(e))}))}),n.length>0&&(e+=(-1===e.indexOf("?")?"?":"&")+n.join("&")),e}},function(e,t,n){"use strict";var r=n(3);e.exports=function(e){var t,n,o,i={};return e?(r.forEach(e.split("\n"),function(e){o=e.indexOf(":"),t=r.trim(e.substr(0,o)).toLowerCase(),n=r.trim(e.substr(o+1)),t&&(i[t]=i[t]?i[t]+", "+n:n)}),i):i}},function(e,t,n){"use strict";var r=n(3);e.exports=function(e,t,n){return r.forEach(n,function(n){e=n(e,t)}),e}},function(e,t,n){"use strict";var r=n(3);e.exports={write:function(e,t,n,o,i,s){var u=[];u.push(e+"="+encodeURIComponent(t)),r.isNumber(n)&&u.push("expires="+new Date(n).toGMTString()),r.isString(o)&&u.push("path="+o),r.isString(i)&&u.push("domain="+i),s===!0&&u.push("secure"),document.cookie=u.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}},function(e,t,n){"use strict";function r(e){var t=e;return s&&(u.setAttribute("href",t),t=u.href),u.setAttribute("href",t),{href:u.href,protocol:u.protocol?u.protocol.replace(/:$/,""):"",host:u.host,search:u.search?u.search.replace(/^\?/,""):"",hash:u.hash?u.hash.replace(/^#/,""):"",hostname:u.hostname,port:u.port,pathname:"/"===u.pathname.charAt(0)?u.pathname:"/"+u.pathname}}var o,i=n(3),s=/(msie|trident)/i.test(navigator.userAgent),u=document.createElement("a");o=r(window.location.href),e.exports=function(e){var t=i.isString(e)?r(e):e;return t.protocol===o.protocol&&t.host===o.host}},function(e,t,n){"use strict";function r(){this.handlers=[]}var o=n(3);r.prototype.use=function(e,t){return this.handlers.push({fulfilled:e,rejected:t}),this.handlers.length-1},r.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},r.prototype.forEach=function(e){o.forEach(this.handlers,function(t){null!==t&&e(t)})},e.exports=r},function(e,t){"use strict";e.exports=function(e){return function(t){return e.apply(null,t)}}}])});`...
exports.go
Source:exports.go
...8 "naksha/service"9 "net/http"10 "strconv"11)12type ExportsController struct {13 *BaseController14 export_service service.ExportService15}16func (ec *ExportsController) Status(w http.ResponseWriter, r *naksha.Request) {17 id := r.UriParams["id"]18 result := ec.export_service.GetStatus(id)19 if result.IsSuccess() {20 if result.GetBoolData("remove_export_id") {21 id_int, _ := strconv.Atoi(id)22 helper.RemoveExportIDFromSession(id_int, r.Session)23 r.Session.Save(r.Request, w)24 }25 }26 json_resp := result.ForJsonResponse()27 ec.RenderJson(w, json_resp)28}29func (ec *ExportsController) Download(w http.ResponseWriter, r *naksha.Request) {30 exports_dir := ec.GetAppConfig().ExportsDir()31 result := ec.export_service.Download(r.UriParams["id"], exports_dir)32 if result.IsSuccess() {33 w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")34 w.Header().Set("Pragma", "no-cache")35 w.Header().Set("Expires", "Sat, 01 Jan 1994 00:10:20 GMT")36 w.Header().Set("Content-Type", result.GetStringData("content_type"))37 attachment := fmt.Sprintf("attachment; filename=\"%v\"", result.GetStringData("filename"))38 w.Header().Set("Content-Disposition", attachment)39 http.ServeFile(w, r.Request, result.GetStringData("file_path"))40 } else {41 ec.RenderHtmlErrors(w, result.GetErrors())42 }43}44func (ec *ExportsController) Index(w http.ResponseWriter, r *naksha.Request) {45 result := ec.export_service.ExportsOfUser(r)46 if result.IsSuccess() {47 ec.RenderHtml(w, r.Session, "exports_index", result.GetData())48 } else {49 ec.RenderHtmlErrors(w, result.GetErrors())50 }51}52func (ec *ExportsController) Delete(w http.ResponseWriter, r *naksha.Request) {53 exports_dir := ec.GetAppConfig().ExportsDir()54 result := ec.export_service.Delete(exports_dir, r.UriParams["id"])55 res := result.ForJsonResponse()56 ec.RenderJson(w, res)57}58func (ec *ExportsController) AuthAuth(req *http.Request, sess *sessions.Session, path_parts []string) bool {59 var is_valid bool60 var user_id int61 tmp := sess.Values["user_id"]62 if tmp == nil {63 is_valid = false64 } else {65 user_id = tmp.(int)66 is_valid = user_id > 067 }68 if is_valid {69 if len(path_parts) == 3 {70 is_valid = ec.export_service.ExportBelongsToUser(path_parts[1], user_id)71 }72 }73 return is_valid74}75func GetExportsHandlers(app_config *naksha.AppConfig, tmpl *template.Template, repository service.Repository) []Route {76 routes := make([]Route, 0)77 var route Route78 validators := make(map[string]string)79 validators["id"] = "^[\\d]+$"80 controller := ExportsController{81 &BaseController{tmpl: tmpl, app_config: app_config},82 repository.GetExportService(),83 }84 route = Route{GET, "/exports/{id}/status", &controller, controller.Status, validators}85 routes = append(routes, route)86 route = Route{GET, "/exports/{id}/download", &controller, controller.Download, validators}87 routes = append(routes, route)88 route = Route{GET, "/exports/index", &controller, controller.Index, validators}89 routes = append(routes, route)90 route = Route{POST, "/exports/{id}/delete", &controller, controller.Delete, validators}91 routes = append(routes, route)92 return routes93}...
json.go
Source:json.go
1package export2import (3 "bytes"4 "encoding/json"5 "hentai_parser/go/module/geziyor/internal"6 "log"7 "os"8)9// JSONLine exports response data as JSON streaming file10type JSONLine struct {11 FileName string12 EscapeHTML bool13 Prefix string14 Indent string15}16// Export exports response data as JSON streaming file17func (e *JSONLine) Export(exports chan interface{}) {18 // Create or append file19 file, err := os.OpenFile(internal.DefaultString(e.FileName, "out.json"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)20 if err != nil {21 log.Printf("Output file creation error: %v\n", err)22 return23 }24 defer file.Close()25 encoder := json.NewEncoder(file)26 encoder.SetEscapeHTML(e.EscapeHTML)27 encoder.SetIndent(e.Prefix, e.Indent)28 // Export data as responses came29 for res := range exports {30 if err := encoder.Encode(res); err != nil {31 log.Printf("JSON encoding error on exporter: %v\n", err)32 }33 }34}35// JSON exports response data as JSON36type JSON struct {37 FileName string38 EscapeHTML bool39}40// Export exports response data as JSON41func (e *JSON) Export(exports chan interface{}) {42 // Create or append file43 file, err := os.OpenFile(internal.DefaultString(e.FileName, "out.json"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)44 if err != nil {45 log.Printf("Output file creation error: %v\n", err)46 return47 }48 defer file.Close()49 file.Write([]byte("[\n"))50 // Export data as responses came51 for res := range exports {52 data, err := jsonMarshalLine(res, e.EscapeHTML)53 if err != nil {54 log.Printf("JSON encoding error on exporter: %v\n", err)55 continue56 }57 file.Write(data)58 }59 // Override on last comma60 stat, err := file.Stat()61 if err != nil {62 file.Write([]byte("]\n"))63 return64 }65 file.WriteAt([]byte("\n]\n"), stat.Size()-2)66}67// jsonMarshalLine adds tab and comma around actual data68func jsonMarshalLine(t interface{}, escapeHTML bool) ([]byte, error) {69 buffer := &bytes.Buffer{}70 encoder := json.NewEncoder(buffer)71 encoder.SetEscapeHTML(escapeHTML)72 buffer.Write([]byte(" ")) // Tab char73 err := encoder.Encode(t) // Write actual data74 buffer.Truncate(buffer.Len() - 1) // Remove last newline char75 buffer.Write([]byte(",\n")) // Write comma and newline char76 return buffer.Bytes(), err77}...
Exports
Using AI Code Generation
1import (2func main() {3 fmt.Println(html.EscapeString("<html>"))4}5<html>6import (7func main() {8 fmt.Println(html.UnescapeString("<html>"))9}
Exports
Using AI Code Generation
1import (2func main() {3 vm := otto.New()4 vm.Run(`5 var html = require('html');6 var htmlObj = new html();7 htmlObj.exports("test",function(){8 console.log("test");9 });10 htmlObj.exports("test2",function(){11 console.log("test2");12 });13 vm.Run(`14 var html = require('html');15 var htmlObj = new html();16 htmlObj.exports("test",function(){17 console.log("test");18 });19 htmlObj.exports("test2",function(){20 console.log("test2");21 });22 fmt.Println("done")23}24import (25func main() {26 vm := otto.New()27 vm.Run(`28 var html = require('html');29 var htmlObj = new html();30 htmlObj.exports("test",function(){31 console.log("test");32 });33 htmlObj.exports("test2",function(){34 console.log("test2");35 });36 fmt.Println("done")37}38import (39func main() {40 vm := otto.New()41 vm.Run(`42 var html = require('html');43 var htmlObj = new html();44 htmlObj.exports("test",function(){45 console.log("test");46 });47 htmlObj.exports("test2",function(){48 console.log("test2");49 });50 fmt.Println("done")51}
Exports
Using AI Code Generation
1import (2func main() {3 vm := otto.New()4 vm.Run(`var html = require("html");`)5 vm.Set("console", map[string]interface{}{6 "log": func(call otto.FunctionCall) otto.Value {7 fmt.Println(call.Argument(0))8 return otto.Value{}9 },10 })11 vm.Run(`12 var html = require("html");13 console.log(html.Exports("Hello World"));`)14}15import (16func main() {17 vm := otto.New()18 vm.Set("console", map[string]interface{}{19 "log": func(call otto.FunctionCall) otto.Value {20 fmt.Println(call.Argument(0))21 return otto.Value{}22 },23 })24 vm.Run(`25 var html = require("html");26 console.log(html.Exports("Hello World"));`)27}28import (29func main() {30 vm := otto.New()31 vm.Set("console", map[string]interface{}{32 "log": func(call otto.FunctionCall) otto.Value {33 fmt.Println(call.Argument(0))34 return otto.Value{}35 },36 })37 vm.Run(`38 var html = require("html");39 console.log(html.Exports("Hello World"));`)40}41import (42func main() {43 vm := otto.New()44 vm.Set("console", map[string]interface{}{45 "log": func(call otto.FunctionCall) otto.Value {46 fmt.Println(call.Argument(0))47 return otto.Value{}48 },49 })50 vm.Run(`51 var html = require("html");52 console.log(html.Exports("Hello World"));`)53}
Exports
Using AI Code Generation
1import (2func main() {3 window := js.Global()4 document := window.Get("document")5 body := document.Get("body")6 div := document.Call("createElement", "div")7 text := document.Call("createTextNode", "Hello World")8 div.Call("appendChild", text)9 body.Call("appendChild", div)10}
Exports
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello World")4 fmt.Println(html.EscapeString("Hello, world!"))5}6import (7func main() {8 fmt.Println("Hello World")9 fmt.Println(html.UnescapeString("Hello, world!"))10}11import (12func main() {13 fmt.Println("Hello World")14 fmt.Println(html.EscapeString("Hello, world!"))15}16import (17func main() {18 fmt.Println("Hello World")19 fmt.Println(html.UnescapeString("Hello, world!"))20}21import (22func main() {23 fmt.Println("Hello World")24 fmt.Println(html.EscapeString("Hello, world!"))25}26import (27func main() {28 fmt.Println("Hello World")29 fmt.Println(html.UnescapeString("Hello, world!"))30}31import (32func main() {33 fmt.Println("Hello World")34 fmt.Println(html.EscapeString("Hello, world!"))35}36import (37func main() {38 fmt.Println("Hello World")39 fmt.Println(html.UnescapeString("Hello, world!"))40}
Exports
Using AI Code Generation
1import (2func main() {3 v := reflect.ValueOf(html)4 t := v.Type()5 for i := 0; i < v.NumMethod(); i++ {6 fmt.Println(t.Method(i).Name)7 }8}9import (10func main() {11 v := reflect.ValueOf(html)12 t := v.Type()13 for i := 0; i < v.NumMethod(); i++ {14 fmt.Println(t.Method(i).Name)15 v.Method(i).Call(nil)16 }17}18import (19func main() {20 v := reflect.ValueOf(html)21 t := v.Type()22 for i := 0; i < v.NumMethod(); i++ {23 fmt.Println(t.Method(i).Name)
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!