Skip to content

Commit

Permalink
New way to add optional parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
milindmadhukar committed Nov 22, 2021
1 parent cb8047f commit a591646
Show file tree
Hide file tree
Showing 15 changed files with 120 additions and 73 deletions.
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,18 @@ package main

import (
"fmt"
"net/http"

piston "github.com/milindmadhukar/go-piston"
)

func main() {
client := piston.GetDefaultClient(http.DefaultClient)
client := piston.CreateDefaultClient()
output, err := client.Execute("python", "", // Passing language. Since no version is specified, it uses the latest supported version.
[]piston.Code{{Content: "inp = input()\nprint(inp[::-1])"}}, // Passing Code.
&piston.OptionalParams{Stdin: "hello world"}) // Passing input as "hello world".
[]piston.Code{
{Content: "inp = input()\nprint(inp[::-1])"},
}, // Passing Code.
piston.Stdin("hello world"), // Passing input as "hello world".
)
if err != nil {
panic(err)
}
Expand Down
8 changes: 3 additions & 5 deletions examples/from_files/main.go → _examples/from_files/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,18 @@ package main

import (
"log"
"net/http"

piston "github.com/milindmadhukar/go-piston"
)

func main() {
client := piston.GetDefaultClient(http.DefaultClient)
paths := []string{"main.py", "test.py"}
files, err := piston.Files(paths)
client := piston.CreateDefaultClient()
files, err := piston.Files("main.py", "test.py")
if err != nil {
log.Fatal(err)
}
output, err := client.Execute("python", "",
files, nil)
files)

log.Println(output.GetOutput())
}
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@ package main

import (
"log"
"net/http"

piston "github.com/milindmadhukar/go-piston"
)

func main() {
client := piston.GetDefaultClient(http.DefaultClient)
client := piston.CreateDefaultClient()
languages := client.GetLanguages()

log.Println("Supported Languages by Piston are: ", *languages)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@ package main

import (
"log"
"net/http"

piston "github.com/milindmadhukar/go-piston"
)

func main() {
client := piston.GetDefaultClient(http.DefaultClient)
client := piston.CreateDefaultClient()
lang := "python"

latestVersion, err := client.GetLatestVersion(lang)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@ package main

import (
"log"
"net/http"

piston "github.com/milindmadhukar/go-piston"
)

func main() {
client := piston.GetDefaultClient(http.DefaultClient)
client := piston.CreateDefaultClient()

runtimes, err := client.GetRuntimes()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,17 @@ package main

import (
"log"
"net/http"

piston "github.com/milindmadhukar/go-piston"
)

func main() {
client := piston.GetDefaultClient(http.DefaultClient)
client := piston.CreateDefaultClient()

output, err := client.Execute("python", "",
[]piston.Code{
{Content: "print('Hello World')"},
}, nil)
})

if err != nil {
log.Fatal(err)
Expand Down
21 changes: 21 additions & 0 deletions _examples/with_input/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package main

import (
"fmt"

piston "github.com/milindmadhukar/go-piston"
)

func main() {
client := piston.CreateDefaultClient()
output, err := client.Execute("python", "", // Passing language. Since no version is specified, it uses the latest supported version.
[]piston.Code{
{Content: "inp = input()\nprint(inp[::-1])"},
}, // Passing Code.
piston.Stdin("hello world"), // Passing input as "hello world".
)
if err != nil {
panic(err)
}
fmt.Println(output.GetOutput())
}
13 changes: 0 additions & 13 deletions models.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package gopiston

import (
"net/http"
"time"
)

/*
Expand Down Expand Up @@ -61,15 +60,3 @@ type PistonResponse struct {
Signal interface{} `json:"signal,omitempty"`
} `json:"run"`
}

/*
Optional Paramaters that can be passed for the execute endpoint
*/
type OptionalParams struct {
Stdin string
Args []string
CompileTimeout time.Duration
RunTimeout time.Duration
CompileMemoryLimit int
RunMemoryLimit int
}
57 changes: 57 additions & 0 deletions params.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package gopiston

import "time"

// Function to pass the Params struct.
type Param func(*Params)

// Struct that contains all piston parameters.
type Params struct {
requestBody *RequestBody
}

// Stdin (optional) The text to pass as stdin to the program. Must be a string or left out. Defaults to blank string.
func Stdin(input string) Param {
return func(param *Params) {
param.requestBody.Stdin = input
}
}

// Args (optional) The arguments to pass to the program. Must be an array or left out. Defaults to [].
func Args(args []string) Param {
return func(param *Params) {
param.requestBody.Args = args
}
}

// CompileTimeout (optional) The maximum time allowed for the compile stage to finish before bailing out in milliseconds. Must be a "time.Duration" object. Defaults to 10 seconds.
func CompileTimeout(timeout time.Duration) Param {

return func(param *Params) {
param.requestBody.CompileTimeout = int(timeout.Seconds())
}
}

// RunTimeout (optional) The maximum time allowed for the run stage to finish before bailing out in milliseconds. Must be a "time.Duration" object. Defaults to 3 seconds.
func RunTimeout(timeout time.Duration) Param {

return func(param *Params) {
param.requestBody.RunTimeout = int(timeout.Seconds())
}
}

// CompileMemoryLimit (optional) The maximum amount of memory the compile stage is allowed to use in bytes. Must be a number or left out. Defaults to -1 (no limit)
func CompileMemoryLimit(limit int) Param {
return func(param *Params) {
param.requestBody.CompileMemoryLimit = limit
}

}

// RunMemoryLimit (optional) The maximum amount of memory the run stage is allowed to use in bytes. Must be a number or left out. Defaults to -1 (no limit)
func RunMemoryLimit(limit int) Param {

return func(param *Params) {
param.requestBody.RunMemoryLimit = limit
}
}
48 changes: 11 additions & 37 deletions piston.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ import (
/*
Creates a default client object and returns it for access to the methods.
*/
func GetDefaultClient(httpClient *http.Client) *Client {
func CreateDefaultClient() *Client {
return &Client{
httpClient: httpClient,
httpClient: http.DefaultClient,
baseUrl: "https://emkc.org/api/v2/piston/",
apiKey: "",
}
Expand Down Expand Up @@ -71,19 +71,19 @@ version (required) The version of the language to use for execution, must be a s
files (required) A Slice of files containing code or other data that should be used for execution. The first file in this array is considered the main file. The name of the files is optional.
Files can be added using path with the "Files()" method. To provide Code directly, provide a slice of "Code" struct.
optionalParams.Stdin (optional) The text to pass as stdin to the program. Must be a string or left out. Defaults to blank string.
Stdin (optional) The text to pass as stdin to the program. Must be a string or left out. Defaults to blank string.
optionalParams.Args (optional) The arguments to pass to the program. Must be an array or left out. Defaults to [].
Args (optional) The arguments to pass to the program. Must be an array or left out. Defaults to [].
optionalParams.CompileTimeout (optional) The maximum time allowed for the compile stage to finish before bailing out in milliseconds. Must be a "time.Duration" object. Defaults to 10 seconds.
CompileTimeout (optional) The maximum time allowed for the compile stage to finish before bailing out in milliseconds. Must be a "time.Duration" object. Defaults to 10 seconds.
optionalParams.RunTimeout (optional) The maximum time allowed for the run stage to finish before bailing out in milliseconds. Must be a "time.Duration" object. Defaults to 3 seconds.
RunTimeout (optional) The maximum time allowed for the run stage to finish before bailing out in milliseconds. Must be a "time.Duration" object. Defaults to 3 seconds.
optionalParams.CompileMemoryLimit (optional) The maximum amount of memory the compile stage is allowed to use in bytes. Must be a number or left out. Defaults to -1 (no limit)
CompileMemoryLimit (optional) The maximum amount of memory the compile stage is allowed to use in bytes. Must be a number or left out. Defaults to -1 (no limit)
optionalParams.RunMemoryLimit (optional) The maximum amount of memory the run stage is allowed to use in bytes. Must be a number or left out. Defaults to -1 (no limit)
RunMemoryLimit (optional) The maximum amount of memory the run stage is allowed to use in bytes. Must be a number or left out. Defaults to -1 (no limit)
*/
func (client *Client) Execute(language string, version string, files []Code, optionalParams *OptionalParams) (*PistonResponse, error) {
func (client *Client) Execute(language string, version string, code []Code, params ...Param) (*PistonResponse, error) {
// Initializing the request body.
reqBody := RequestBody{}

Expand All @@ -102,35 +102,9 @@ func (client *Client) Execute(language string, version string, files []Code, opt
}

reqBody.Version = version
reqBody.Files = files

// Handling Optional parameters for the request body.
if optionalParams != nil {

if stdin := optionalParams.Stdin; stdin != "" {
reqBody.Stdin = stdin
}

if args := optionalParams.Args; args != nil {
reqBody.Args = args
}

if compileTimeout := optionalParams.CompileTimeout; compileTimeout.Milliseconds() != 0 {
reqBody.CompileTimeout = int(compileTimeout.Milliseconds())
}

if runTimeout := optionalParams.RunTimeout; runTimeout.Microseconds() != 0 {
reqBody.RunTimeout = int(runTimeout.Milliseconds())
}
reqBody.Files = code

if compileMemoryLimit := optionalParams.CompileMemoryLimit; compileMemoryLimit != 0 {
reqBody.CompileMemoryLimit = compileMemoryLimit
}

if runMemoryLimit := optionalParams.RunMemoryLimit; runMemoryLimit != 0 {
reqBody.RunMemoryLimit = runMemoryLimit
}
}
reqBody = *processParams(&reqBody, params...)

// Getting a json bytes.
bytesBody, err := json.Marshal(reqBody)
Expand Down
6 changes: 2 additions & 4 deletions piston_test.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
package gopiston

import (
"net/http"
"testing"
"time"
)

var client = GetDefaultClient(http.DefaultClient)
var client = CreateDefaultClient()

func assert(expected, got interface{}, t *testing.T) {
if expected != got {
Expand All @@ -30,7 +29,6 @@ func TestExecutionCode(t *testing.T) {
output, err := client.Execute(
"python", "",
[]Code{{Content: "print([i for i in range(4)])"}},
nil,
)

if err != nil {
Expand All @@ -49,7 +47,7 @@ func TestTimeout(t *testing.T) {
Content: "import time\nprint('before sleep')\ntime.sleep(3)\nprint('after sleep')",
},
},
&OptionalParams{RunTimeout: 2 * time.Second},
RunTimeout(2*time.Second),
)

if err != nil {
Expand Down
2 changes: 2 additions & 0 deletions test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

go clean -testcache && go test ./... -v -cover | sed ''/PASS/s//$(printf "\033[32mPASS\033[0m")/'' | sed ''/FAIL/s//$(printf "\033[31mFAIL\033[0m")/'' | sed ''/RUN/s//$(printf "\033[33mRUN\033[0m")/'' | GREP_COLOR='01;32' grep -E --color 'ok.*$|^.*ok.*$|$'
14 changes: 13 additions & 1 deletion utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,17 @@ import (
"os"
)

func processParams(body *RequestBody, params ...Param) *RequestBody {
p := Params{
requestBody: body,
}
for _, param := range params {
param(&p)
}

return body
}

/*
Returns the output of the given code.
*/
Expand All @@ -20,7 +31,7 @@ func (resp *PistonResponse) GetOutput() string {
Utility method to pass file paths instead of actual code in the string.
Providing a slice of paths will send all the files.
*/
func Files(paths []string) ([]Code, error) {
func Files(paths ...string) ([]Code, error) {
var files []Code

for _, path := range paths {
Expand Down Expand Up @@ -112,6 +123,7 @@ func handleStatusCode(code int, respBody string) error {

// Handles sending the request to the Piston API and returing a response.
func (client *Client) handleRequest(method string, url string, body *bytes.Reader) (*http.Response, error) {
// HACK: Why is this needed?
if body == nil {
body = &bytes.Reader{}
}
Expand Down

0 comments on commit a591646

Please sign in to comment.