How to use CopyFile method of internal Package

Best Ginkgo code snippet using internal.CopyFile

Run Ginkgo automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

gtk.go

Source: gtk.go Github

copy
1package template
2
3import (
4	"fmt"
5	"os"
6	"os/exec"
7	"path"
8	"syscall"
9
10	"go-create/internal/copyFile"
11)
12
13const gtkBasePath = "/home/per/code/templates/gtk-startup"
14
15type gtkTemplate struct {
16	project *Project
17}
18
19func (t *gtkTemplate) create() {
20	t.createProjectFolders()
21	t.copyProjectFiles()
22	t.goMod()
23	t.gitInit()
24}
25
26func (t *gtkTemplate) createProjectFolders() {
27	// Create main project directory
28	createFolder(t.project.Path)
29
30	// Create project folders
31	createFolder(path.Join(t.project.Path, "assets"))
32	createFolder(path.Join(t.project.Path, "build"))
33	createFolder(path.Join(t.project.Path, "cmd"))
34	createFolder(path.Join(t.project.Path, "cmd", t.project.Name))
35	createFolder(path.Join(t.project.Path, "internal"))
36	createFolder(path.Join(t.project.Path, "internal", t.project.Name))
37	createFolder(path.Join(t.project.Path, ".run"))
38}
39
40func (t *gtkTemplate) copyProjectFiles() {
41	// BASE FILES
42	cfo := &copyFile.CopyFileOperation{
43		From:        &copyFile.CopyFilePath{BasePath: gtkBasePath},
44		To:          &copyFile.CopyFilePath{BasePath: t.project.Path},
45		ProjectName: t.project.Name,
46		Description: t.project.Description,
47	}
48	cfo.SetFileName(".gitignore")
49	cfo.CopyFile()
50	cfo.SetFileName("readme.md")
51	cfo.CopyFile()
52
53	// ASSETS
54	cfo.SetRelativePath("assets")
55	cfo.SetFileName("application.png")
56	cfo.CopyFile()
57	cfo.SetFileName("main.glade")
58	cfo.CopyFile()
59
60	// MAIN FILES
61	cfo.SetFileName("main.go")
62	cfo.From.RelativePath = "cmd/gtk-startup"
63	cfo.To.RelativePath = fmt.Sprintf("cmd/%s", t.project.Name)
64	cfo.CopyFile()
65
66	// INTERNAL FILES
67	cfo.From.RelativePath = "internal/gtk-startup"
68	cfo.To.RelativePath = fmt.Sprintf("internal/%s", t.project.Name)
69	cfo.SetFileName("mainForm.go")
70	cfo.CopyFile()
71	cfo.SetFileName("extraForm.go")
72	cfo.CopyFile()
73	cfo.SetFileName("dialog.go")
74	cfo.CopyFile()
75	cfo.SetFileName("aboutDialog.go")
76	cfo.CopyFile()
77
78	// RUN CONFIGURATION
79	cfo.SetRelativePath(".run")
80	cfo.From.FileName = "project-name.run.xml"
81	cfo.To.FileName = fmt.Sprintf("%s.run.xml", t.project.Name)
82	cfo.CopyFile()
83}
84
85func (t *gtkTemplate) goMod() {
86	fmt.Printf("Running : go mod init github.com/hultan/%s...\n", t.project.Name)
87
88	command := fmt.Sprintf("cd %s;go mod init github.com/hultan/%s", t.project.Path, t.project.Name)
89	cmd := exec.Command("bash", "-c", command)
90	// Forces the new process to detach from the GitDiscover process
91	// so that it does not die when GitDiscover dies
92	cmd.SysProcAttr = &syscall.SysProcAttr{
93		Setpgid: true,
94	}
95
96	output, err := cmd.CombinedOutput()
97	if err != nil {
98		_, _ = fmt.Fprintf(os.Stderr, "Failed to run : go mod init github.com/hultan/%s : %v", t.project.Name, err)
99	}
100	err = cmd.Process.Release()
101	if err != nil {
102		_, _ = fmt.Fprintf(os.Stderr, "Failed to release process (goMod) : %v", err)
103	}
104
105	fmt.Println(string(output))
106}
107
108func (t *gtkTemplate) gitInit() {
109	fmt.Println("Running : git init...")
110
111	command := fmt.Sprintf("cd %s;git init", t.project.Path)
112	cmd := exec.Command("bash", "-c", command)
113	// Forces the new process to detach from the GitDiscover process
114	// so that it does not die when GitDiscover dies
115	cmd.SysProcAttr = &syscall.SysProcAttr{
116		Setpgid: true,
117	}
118
119	output, err := cmd.CombinedOutput()
120	if err != nil {
121		_, _ = fmt.Fprintf(os.Stderr, "Failed to run : git init : %v", err)
122	}
123	err = cmd.Process.Release()
124	if err != nil {
125		_, _ = fmt.Fprintf(os.Stderr, "Failed to release process (gitInit): %v", err)
126	}
127
128	fmt.Println(string(output))
129}
130
Full Screen

normal.go

Source: normal.go Github

copy
1package template
2
3import (
4	"fmt"
5	"os"
6	"os/exec"
7	"path"
8	"syscall"
9
10	"go-create/internal/copyFile"
11)
12
13const normalBasePath = "/home/per/code/templates/normal"
14
15type normalTemplate struct {
16	project *Project
17}
18
19func (t *normalTemplate) create() {
20	t.createProjectFolders()
21	t.copyProjectFiles()
22	t.goMod()
23	t.gitInit()
24}
25
26func (t *normalTemplate) createProjectFolders() {
27	// Create main project directory
28	createFolder(t.project.Path)
29
30	// Create project folders
31	createFolder(path.Join(t.project.Path, "assets"))
32	createFolder(path.Join(t.project.Path, "build"))
33	createFolder(path.Join(t.project.Path, "cmd"))
34	createFolder(path.Join(t.project.Path, "cmd", t.project.Name))
35	createFolder(path.Join(t.project.Path, "internal"))
36	createFolder(path.Join(t.project.Path, "internal", t.project.Name))
37	createFolder(path.Join(t.project.Path, ".run"))
38}
39
40func (t *normalTemplate) copyProjectFiles() {
41	// BASE FILES
42	cfo := &copyFile.CopyFileOperation{
43		From:        &copyFile.CopyFilePath{BasePath: normalBasePath},
44		To:          &copyFile.CopyFilePath{BasePath: t.project.Path},
45		ProjectName: t.project.Name,
46		Description: t.project.Description,
47	}
48	cfo.SetFileName(".gitignore")
49	cfo.CopyFile()
50	cfo.SetFileName("readme.md")
51	cfo.CopyFile()
52
53	// ASSETS
54	cfo.SetRelativePath("assets")
55	cfo.SetFileName("application.png")
56	cfo.CopyFile()
57
58	// MAIN FILES
59	cfo.SetFileName("main.go")
60	cfo.From.RelativePath = "cmd/normal"
61	cfo.To.RelativePath = fmt.Sprintf("cmd/%s", t.project.Name)
62	cfo.CopyFile()
63
64	// INTERNAL FILES
65	cfo.From.RelativePath = "internal/normal"
66	cfo.To.RelativePath = fmt.Sprintf("internal/%s", t.project.Name)
67	cfo.SetFileName("normal.go")
68	cfo.CopyFile()
69
70	// RUN CONFIGURATION
71	cfo.SetRelativePath(".run")
72	cfo.From.FileName = "project-name.run.xml"
73	cfo.To.FileName = fmt.Sprintf("%s.run.xml", t.project.Name)
74	cfo.CopyFile()
75}
76
77func (t *normalTemplate) goMod() {
78	fmt.Printf("Running : go mod init github.com/hultan/%s...\n", t.project.Name)
79
80	command := fmt.Sprintf("cd %s;go mod init github.com/hultan/%s", t.project.Path, t.project.Name)
81	cmd := exec.Command("bash", "-c", command)
82	// Forces the new process to detach from the GitDiscover process
83	// so that it does not die when GitDiscover dies
84	cmd.SysProcAttr = &syscall.SysProcAttr{
85		Setpgid: true,
86	}
87
88	output, err := cmd.CombinedOutput()
89	if err != nil {
90		_, _ = fmt.Fprintf(os.Stderr, "Failed to run : go mod init github.com/hultan/%s : %v", t.project.Name, err)
91	}
92	err = cmd.Process.Release()
93	if err != nil {
94		_, _ = fmt.Fprintf(os.Stderr, "Failed to release process (goMod) : %v", err)
95	}
96
97	fmt.Println(string(output))
98}
99
100func (t *normalTemplate) gitInit() {
101	fmt.Println("Running : git init...")
102
103	command := fmt.Sprintf("cd %s;git init", t.project.Path)
104	cmd := exec.Command("bash", "-c", command)
105	// Forces the new process to detach from the GitDiscover process
106	// so that it does not die when GitDiscover dies
107	cmd.SysProcAttr = &syscall.SysProcAttr{
108		Setpgid: true,
109	}
110
111	output, err := cmd.CombinedOutput()
112	if err != nil {
113		_, _ = fmt.Fprintf(os.Stderr, "Failed to run : git init : %v", err)
114	}
115	err = cmd.Process.Release()
116	if err != nil {
117		_, _ = fmt.Fprintf(os.Stderr, "Failed to release process (gitInit): %v", err)
118	}
119
120	fmt.Println(string(output))
121}
122
Full Screen

handlers.go

Source: handlers.go Github

copy
1// Copyright 2019-2020 The Pythia Authors.
2// This file is part of Pythia.
3//
4// Pythia is free software: you can redistribute it and/or modify
5// it under the terms of the GNU Affero General Public License as published by
6// the Free Software Foundation, version 3 of the License.
7//
8// Pythia is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11// GNU Affero General Public License for more details.
12//
13// You should have received a copy of the GNU Affero General Public License
14// along with Pythia.  If not, see <http://www.gnu.org/licenses/>.
15
16package handler
17
18import (
19	"encoding/json"
20	"errors"
21	"fmt"
22	"io"
23	"io/ioutil"
24	"log"
25	"net/http"
26	"os"
27	"os/exec"
28	"strconv"
29	"strings"
30
31	"github.com/gorilla/mux"
32	"github.com/mitchellh/mapstructure"
33	"github.com/pythia-project/pythia-core/go/src/pythia"
34	"github.com/pythia-project/pythia-server/server"
35)
36
37// HealthHandler handles route /api/health
38func HealthHandler(w http.ResponseWriter, r *http.Request) {
39	w.Header().Set("Content-Type", "application/json")
40	conn, err := pythia.Dial(server.Conf.Address.Queue)
41	if err == nil {
42		conn.Close()
43	}
44	info := server.HealthInfo{err == nil}
45
46	data, err := json.Marshal(info)
47	if err != nil {
48		w.WriteHeader(http.StatusInternalServerError)
49		return
50	}
51
52	w.WriteHeader(http.StatusOK)
53	w.Write(data)
54}
55
56// ExecuteHandler handles route /api/execute
57func ExecuteHandler(w http.ResponseWriter, r *http.Request) {
58	request := server.SubmisssionRequest{}
59	err := json.NewDecoder(r.Body).Decode(&request)
60	if err != nil {
61		log.Println(err)
62		w.WriteHeader(http.StatusBadRequest)
63		return
64	}
65
66	var async bool
67	if r.FormValue("async") == "" {
68		async = false
69	} else {
70		async, err = strconv.ParseBool(r.FormValue("async"))
71		if err != nil {
72			log.Println(err)
73			w.WriteHeader(http.StatusBadRequest)
74			return
75		}
76	}
77
78	executeTask(request, async, w)
79}
80
81// ListEnvironments lists all the available environments.
82func ListEnvironments(w http.ResponseWriter, r *http.Request) {
83	files, err := ioutil.ReadDir(server.Conf.Path.Environments)
84	if err != nil {
85		w.WriteHeader(http.StatusInternalServerError)
86		return
87	}
88
89	environments := make([]server.Environment, 0)
90	for _, f := range files {
91		name := f.Name()
92		if strings.HasSuffix(name, ".sfs") {
93			environments = append(environments, server.Environment{Name: name[:len(name)-4]})
94		}
95	}
96
97	data, err := json.Marshal(environments)
98	if err != nil {
99		w.WriteHeader(http.StatusInternalServerError)
100		return
101	}
102
103	w.Header().Set("Content-Type", "application/json")
104	w.WriteHeader(http.StatusOK)
105	w.Write(data)
106}
107
108// GetEnvironment retrieves one given environment.
109func GetEnvironment(w http.ResponseWriter, r *http.Request) {
110	vars := mux.Vars(r)
111	envpath := fmt.Sprintf("%s/%s.env", server.Conf.Path.Environments, vars["envid"])
112	if _, err := os.Stat(envpath); err == nil {
113		if content, err := ioutil.ReadFile(envpath); err == nil {
114			w.Header().Set("Content-Type", "application/json")
115			w.WriteHeader(http.StatusOK)
116			w.Write(content)
117			return
118		}
119
120	} else if os.IsNotExist(err) {
121		w.WriteHeader(http.StatusNotFound)
122		return
123	}
124
125	w.WriteHeader(http.StatusInternalServerError)
126}
127
128// ListTasks lists all the available tasks.
129func ListTasks(w http.ResponseWriter, r *http.Request) {
130	files, err := ioutil.ReadDir(server.Conf.Path.Tasks)
131	if err != nil {
132		w.WriteHeader(http.StatusInternalServerError)
133		return
134	}
135
136	tasks := make([]server.Task, 0)
137	for _, f := range files {
138		name := f.Name()
139		if strings.HasSuffix(name, ".task") {
140			tasks = append(tasks, server.Task{Taskid: name[:len(name)-5]})
141		}
142	}
143
144	data, err := json.Marshal(tasks)
145	if err != nil {
146		w.WriteHeader(http.StatusInternalServerError)
147		return
148	}
149
150	w.Header().Set("Content-Type", "application/json")
151	w.WriteHeader(http.StatusOK)
152	w.Write(data)
153}
154
155// CreateTask creates a new task.
156func CreateTask(w http.ResponseWriter, r *http.Request) {
157	request := server.TaskCreationRequest{
158		Type: "raw",
159		Limits: server.Limits{
160			Time:   60,
161			Memory: 32,
162			Disk:   50,
163			Output: 1024,
164		},
165	}
166	err := json.NewDecoder(r.Body).Decode(&request)
167	if err != nil {
168		log.Println(err)
169		w.WriteHeader(http.StatusBadRequest)
170		return
171	}
172	// Check whether a task with the same ID already exists
173	taskDir := fmt.Sprintf("%s/%s", server.Conf.Path.Tasks, request.Taskid)
174	taskFile := fmt.Sprintf("%s.task", taskDir)
175	if _, err := os.Stat(fmt.Sprintf("%s.task", taskDir)); err == nil {
176		log.Println("Task id", request.Taskid, "already exists.")
177		w.WriteHeader(http.StatusBadRequest)
178		return
179	}
180
181	// Create the task directory
182	if err := os.Mkdir(taskDir, 0755); err != nil {
183		log.Println("Impossible to create task directory:", err)
184		w.WriteHeader(http.StatusInternalServerError)
185		return
186	}
187
188	// Create the task file
189	task := pythia.Task{
190		Environment: request.Environment,
191		TaskFS:      request.Taskid + ".sfs",
192		Limits:      request.Limits,
193	}
194	file, _ := json.MarshalIndent(task, "", "  ")
195	_ = ioutil.WriteFile(taskFile, file, 0644)
196
197	// Copy the files from the template
198	switch request.Type {
199	case "input-output":
200		_ = os.Mkdir(taskDir+"/config", 0755)
201		_ = os.Mkdir(taskDir+"/scripts", 0755)
202		_ = os.Mkdir(taskDir+"/skeleton", 0755)
203
204		templateDir := "templates/input-output/" + request.Environment
205		_ = copyFile(templateDir+"/control", taskDir+"/control", 0755)
206		_ = copyFile(templateDir+"/scripts/pythia-iot", taskDir+"/scripts/pythia-iot", 0755)
207
208		switch request.Environment {
209		case "ada":
210			_ = copyFile(templateDir+"/scripts/execute.sh", taskDir+"/scripts/execute.sh", 0755)
211			_ = copyFile(templateDir+"/skeleton/program.adb", taskDir+"/skeleton/program.adb", 0755)
212		case "algol68":
213			_ = copyFile(templateDir+"/skeleton/program.alg", taskDir+"/skeleton/program.alg", 0755)
214		case "bash":
215			_ = copyFile(templateDir+"/skeleton/program.sh", taskDir+"/skeleton/program.sh", 0755)
216		case "c":
217			_ = copyFile(templateDir+"/scripts/execute.sh", taskDir+"/scripts/execute.sh", 0755)
218			_ = copyFile(templateDir+"/skeleton/program.c", taskDir+"/skeleton/program.c", 0755)
219		case "cpp":
220			_ = copyFile(templateDir+"/scripts/execute.sh", taskDir+"/scripts/execute.sh", 0755)
221			_ = copyFile(templateDir+"/skeleton/program.cpp", taskDir+"/skeleton/program.cpp", 0755)
222		case "golang":
223			_ = copyFile(templateDir+"/scripts/execute.sh", taskDir+"/scripts/execute.sh", 0755)
224			_ = copyFile(templateDir+"/skeleton/program.go", taskDir+"/skeleton/program.go", 0755)
225		case "java":
226			_ = copyFile(templateDir+"/scripts/execute.sh", taskDir+"/scripts/execute.sh", 0755)
227			_ = copyFile(templateDir+"/skeleton/Program.java", taskDir+"/skeleton/Program.java", 0755)
228		case "lua":
229			_ = copyFile(templateDir+"/skeleton/program.lua", taskDir+"/skeleton/program.lua", 0755)
230		case "nodejs":
231			_ = copyFile(templateDir+"/skeleton/program.js", taskDir+"/skeleton/program.js", 0755)
232		case "php7":
233			_ = copyFile(templateDir+"/skeleton/program.php", taskDir+"/skeleton/program.php", 0755)
234		case "prolog":
235			_ = copyFile(templateDir+"/skeleton/program.pl", taskDir+"/skeleton/program.pl", 0755)
236		case "python":
237			_ = copyFile(templateDir+"/skeleton/program.py", taskDir+"/skeleton/program.py", 0755)
238		case "rexx":
239			_ = copyFile(templateDir+"/skeleton/program.rexx", taskDir+"/skeleton/program.rexx", 0755)
240		case "rust":
241			_ = copyFile(templateDir+"/scripts/execute.sh", taskDir+"/scripts/execute.sh", 0755)
242			_ = copyFile(templateDir+"/skeleton/program.rs", taskDir+"/skeleton/program.rs", 0755)
243		case "tcl":
244			_ = copyFile(templateDir+"/skeleton/program.tcl", taskDir+"/skeleton/program.tcl", 0755)
245		}
246
247		// Save the configuration
248		config := server.InputOutputTaskConfig{}
249		if mapstructure.Decode(request.Config, &config) == nil {
250			file, _ = json.MarshalIndent(config, "", "  ")
251			_ = ioutil.WriteFile(taskDir+"/config/test.json", file, 0644)
252		}
253
254	case "unit-testing":
255		_ = os.Mkdir(taskDir+"/config", 0755)
256		_ = os.Mkdir(taskDir+"/scripts", 0755)
257		_ = os.Mkdir(taskDir+"/skeleton", 0755)
258		_ = os.Mkdir(taskDir+"/static", 0755)
259		_ = os.Mkdir(taskDir+"/static/lib", 0755)
260
261		templateDir := "templates/unit-testing/" + request.Environment
262		_ = copyFile(templateDir+"/control", taskDir+"/control", 0755)
263		_ = copyFile(templateDir+"/scripts/pythia-utbt", taskDir+"/scripts/pythia-utbt", 0755)
264
265		switch request.Environment {
266		case "python":
267			_ = copyFile(templateDir+"/scripts/execute.py", taskDir+"/scripts/execute.py", 0755)
268			_ = copyFile(templateDir+"/static/lib/__init__.py", taskDir+"/static/lib/__init__.py", 0755)
269			_ = copyFile(templateDir+"/static/lib/pythia.py", taskDir+"/static/lib/pythia.py", 0755)
270		case "java":
271			_ = copyFile(templateDir+"/scripts/execute.sh", taskDir+"/scripts/execute.sh", 0755)
272			_ = copyFile(templateDir+"/static/lib/commons-csv-1.7.jar", taskDir+"/static/lib/commons-csv-1.7.jar", 0755)
273			_ = copyFile(templateDir+"/static/lib/json-20180813.jar", taskDir+"/static/lib/json-20180813.jar", 0755)
274			_ = copyFile(templateDir+"/static/lib/pythia-1.0.jar", taskDir+"/static/lib/pythia-1.0.jar", 0755)
275		}
276
277		// Save the configuration
278		config := server.UnitTestingTaskConfig{}
279		if mapstructure.Decode(request.Config, &config) == nil {
280			file, _ := json.MarshalIndent(config.Spec, "", "  ")
281			_ = ioutil.WriteFile(taskDir+"/config/spec.json", file, 0644)
282			file, _ = json.MarshalIndent(config.Test, "", "  ")
283			_ = ioutil.WriteFile(taskDir+"/config/test.json", file, 0644)
284
285			// Create skeletons files
286			content := ""
287			switch request.Environment {
288			case "python":
289				params := make([]string, 0)
290				for _, elem := range config.Spec.Args {
291					params = append(params, elem.Name)
292				}
293				content = fmt.Sprintf("# -*- coding: utf-8 -*-\[email protected]@[email protected]@\ndef %s(%s):\[email protected]    @[email protected]@\n", config.Spec.Name, strings.Join(params, ", "))
294				ioutil.WriteFile(taskDir+"/skeleton/program.py", []byte(content), 0755)
295			case "java":
296				params := make([]string, 0)
297				for _, elem := range config.Spec.Args {
298					params = append(params, elem.Type+" "+elem.Name)
299				}
300				content = fmt.Sprintf("@@[email protected]@\n\npublic class Program\n{\n\tpublic static %s %s (%s)\n\t{\[email protected]\t\[email protected]@@\n\t}\n}\n", config.Spec.Return, config.Spec.Name, strings.Join(params, ", "))
301				ioutil.WriteFile(taskDir+"/skeleton/Program.java", []byte(content), 0755)
302			}
303
304			// Create solution file
305			file, _ = json.MarshalIndent(config.Solution, "", "  ")
306			_ = ioutil.WriteFile(taskDir+"/config/solution.json", file, 0644)
307		}
308	}
309
310	// Compile the SFS
311	// mksquashfs TASK TASK.sfs -all-root -comp lzo -noappend
312	wd, _ := os.Getwd()
313	_ = os.Chdir(server.Conf.Path.Tasks)
314	exec.Command("mksquashfs", request.Taskid, request.Taskid+".sfs", "-all-root", "-comp", "lzo", "-noappend").Run()
315	_ = os.Chdir(wd)
316
317	w.WriteHeader(http.StatusOK)
318}
319
320// GetTask retrieves one given task.
321func GetTask(w http.ResponseWriter, r *http.Request) {
322	vars := mux.Vars(r)
323	taskpath := fmt.Sprintf("%s/%s.task", server.Conf.Path.Tasks, vars["taskid"])
324	if _, err := os.Stat(taskpath); err == nil {
325		if content, err := ioutil.ReadFile(taskpath); err == nil {
326			w.Header().Set("Content-Type", "application/json")
327			w.WriteHeader(http.StatusOK)
328			w.Write(content)
329			return
330		}
331
332	} else if os.IsNotExist(err) {
333		w.WriteHeader(http.StatusNotFound)
334		return
335	}
336
337	w.WriteHeader(http.StatusInternalServerError)
338}
339
340// DeleteTask deletes one given task.
341func DeleteTask(w http.ResponseWriter, r *http.Request) {
342	vars := mux.Vars(r)
343	taskdir := fmt.Sprintf("%s/%s", server.Conf.Path.Tasks, vars["taskid"])
344	if _, err := os.Stat(taskdir); err == nil {
345		_ = os.RemoveAll(taskdir)
346		_ = os.Remove(taskdir + ".sfs")
347		_ = os.Remove(taskdir + ".task")
348
349		w.WriteHeader(http.StatusOK)
350		return
351	} else if os.IsNotExist(err) {
352		w.WriteHeader(http.StatusNotFound)
353		return
354	}
355
356	w.WriteHeader(http.StatusInternalServerError)
357}
358
359// ExecuteTask executes one given task.
360func ExecuteTask(w http.ResponseWriter, r *http.Request) {
361	request := server.SubmisssionRequest{}
362	err := json.NewDecoder(r.Body).Decode(&request)
363	if err != nil {
364		log.Println(err)
365		w.WriteHeader(http.StatusBadRequest)
366		return
367	}
368
369	vars := mux.Vars(r)
370	taskpath := fmt.Sprintf("%s/%s.sfs", server.Conf.Path.Tasks, vars["taskid"])
371	if _, err := os.Stat(taskpath); err != nil {
372		if os.IsNotExist(err) {
373			w.WriteHeader(http.StatusNotFound)
374			return
375		}
376	}
377	request.Tid = vars["taskid"]
378
379	var async bool
380	if r.FormValue("async") == "" {
381		async = false
382	} else {
383		async, err = strconv.ParseBool(r.FormValue("async"))
384		if err != nil {
385			log.Println(err)
386			w.WriteHeader(http.StatusBadRequest)
387			return
388		}
389	}
390
391	executeTask(request, async, w)
392}
393
394func copyFile(src string, dst string, perms os.FileMode) (err error) {
395	var from, to *os.File
396	if from, err = os.Open(src); err == nil {
397		defer from.Close()
398		if to, err = os.OpenFile(dst, os.O_RDWR|os.O_CREATE, perms); err == nil {
399			defer to.Close()
400			_, err = io.Copy(to, from)
401		}
402	}
403	return
404}
405
406func executeTask(request server.SubmisssionRequest, async bool, w http.ResponseWriter) {
407	if async && request.Callback == "" {
408		w.WriteHeader(http.StatusBadRequest)
409		return
410	}
411
412	// Connection to the pool and execution of the task
413	conn := pythia.DialRetry(server.Conf.Address.Queue)
414
415	var task pythia.Task
416
417	file, err := os.Open(fmt.Sprintf("%v/%v.task", server.Conf.Path.Tasks, request.Tid))
418	if err != nil {
419		log.Println(err)
420		w.WriteHeader(http.StatusBadRequest)
421		return
422	}
423
424	err = json.NewDecoder(file).Decode(&task)
425	if err != nil {
426		log.Println(err)
427		w.WriteHeader(http.StatusInternalServerError)
428		return
429	}
430	conn.Send(pythia.Message{
431		Message: pythia.LaunchMsg,
432		Id:      "test",
433		Task:    &task,
434		Input:   request.Input,
435	})
436
437	receive := func() (res []byte, err error) {
438		msg, ok := <-conn.Receive()
439
440		if !ok {
441			err = errors.New("Pythia request failed")
442			return
443		}
444
445		result := server.SubmisssionResult{request.Tid, string(msg.Status), msg.Output}
446
447		res, err = json.Marshal(result)
448		if err != nil {
449			return
450		}
451		return
452	}
453
454	if async {
455		go func() {
456			byteData, err := receive()
457			if err != nil {
458				log.Println(err)
459				w.WriteHeader(http.StatusInternalServerError)
460				return
461			}
462			conn.Close()
463			data := strings.NewReader(string(byteData))
464			postResponse, err := http.Post(request.Callback, "application/json", data)
465			if err != nil {
466				log.Println(err)
467				return
468			}
469			log.Println(postResponse)
470		}()
471	} else {
472		byteData, err := receive()
473		if err != nil {
474			log.Println(err)
475			w.WriteHeader(http.StatusInternalServerError)
476			return
477		}
478		conn.Close()
479		w.Header().Set("Content-Type", "application/json")
480		w.Header().Set("Access-Control-Allow-Origin", "*")
481		w.WriteHeader(http.StatusOK)
482		w.Write(byteData)
483	}
484}
485
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used method in

Trigger CopyFile code on LambdaTest Cloud Grid

Execute automation tests with CopyFile on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)