Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
dudongcheng committed Nov 17, 2019
0 parents commit 83137df
Show file tree
Hide file tree
Showing 24 changed files with 2,086 additions and 0 deletions.
17 changes: 17 additions & 0 deletions .github/workflows/maven.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: mvn

on: [push]

jobs:
build:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v1
- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Build with Maven
run: make build
32 changes: 32 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Compiled class file
*.class

# Log file
*.log

# BlueJ files
*.ctxt

# Mobile Tools for Java (J2ME)
.mtj.tmp/

# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

# mac
.DS_Store

# target
mirage-cli/target
mirage-core/target
*.iml
.idea
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 dongcheng.du

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
19 changes: 19 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
PREFIX = /usr/local

all: build

build:
mvn clean -DskipTests=true package

install: mirage-cli/target/mirage-cli-*.jar
install -v -p -b mirage-cli/target/mirage-cli-*.jar ${PREFIX}/bin/mirage

#mirage-cli/target/mirage-cli-*.jar: build

uninstall:
rm -rf ${PREFIX}/bin/mirage

clean:
mvn clean

.PHONY: all build install uninstall clean
125 changes: 125 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# mirage

![](https://github.com/six-ddc/mirage/workflows/mvn/badge.svg)

A web DSL to easily create a simple HTTP server

## Features

- **DSL syntax:** Human-readable [DSL](http://docs.groovy-lang.org/docs/latest/html/documentation/core-domain-specific-languages.html) syntax, let us be more intuitive write we need to provide HTTP server.

- **Data Faker:** Add [Java Faker](https://github.com/DiUS/java-faker) for generating mock data such as names, addresses, and phone numbers.

- **Out of the box:** After a simple installation, you run it on CLI without any configuration or modification.

- **File watching:** Server will automatically reload when the specified files has been changed.

- **High performance:** The Web framework implementation is based on [Spring Boot](https://spring.io/projects/spring-boot), and DSL syntax is based on [Groovy](http://groovy-lang.org/).

## Installation

```shell
make && make install
```

## Usage

```
usage: mirage [-p <port>] [-c <script>] [file|dir]...
A web DSL to easily create a simple HTTP server
-c,--script <script> raw dsl script
--ext <ext> specify DSL file extension when the command
arguments contains directory, (default: mir)
-h,--help print help message
-n,--interval <interval> specify update interval in seconds
-p,--port <port> specify server port (default 8080)
For more information, see https://github.com/six-ddc/mirage
```

### Examples

#### hello world

```shell
mirage -c 'get("/hello") { resp.println "world!"}'
# curl http://127.0.0.1:8080/hello
# world!
```

#### file server

```shell
mirage -c 'get("/a.mp4") { resp.file "a.mp4" }'
# open http://127.0.0.1:8080/a.mp4
```

#### file browser

```shell
mirage -c 'get("/files/**") { resp.index "." }'
# curl http://127.0.0.1:8080/files/pom.xml
```

#### mock user data

* create file `user.mir` and typing

```groovy
handle path: '/user/{uid}/get', method: "GET", {
sleep 100.millisecond
resp.json {
id req.pathVariables.uid
name random.forRegex(/[A-Z][a-z]{3,10}/)
t new Date()
data {
contact 1..2, {
id it
name faker.name().name()
address faker.address().fullAddress()
phone faker.phoneNumber().cellPhone()
}
}
}
}
```

* run

```shell
mirage user.mir
```

* test server

```json
$ curl -s http://127.0.0.1:8080/user/1234/get | jq .
{
"id": "1234",
"name": "Astn",
"t": "2019-11-17T04:04:55+0000",
"data": {
"contact": [
{
"id": 1,
"name": "Bryan Bashirian",
"address": "22474 Bashirian Ways, New Thanhfurt, MA 32424-5437",
"phone": "(973) 158-7100"
},
{
"id": 2,
"name": "Charley Jast",
"address": "526 Corkery Rue, Lake Moises, MO 28747",
"phone": "1-418-198-2865"
}
]
}
}
```

## License

[MIT](https://tldrlegal.com/license/mit-license)
46 changes: 46 additions & 0 deletions mirage-cli/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>mirage</artifactId>
<groupId>com.github.six-ddc</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>mirage-cli</artifactId>
<packaging>jar</packaging>

<dependencies>
<dependency>
<groupId>com.github.six-ddc</groupId>
<artifactId>mirage-core</artifactId>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.4</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
<embeddedLaunchScript>src/main/resources/launch.script</embeddedLaunchScript>
</configuration>
</plugin>
</plugins>
</build>

</project>
103 changes: 103 additions & 0 deletions mirage-cli/src/main/java/com/github/sixddc/mirage/Application.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package com.github.sixddc.mirage;

import org.apache.commons.cli.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@SpringBootApplication
@EnableScheduling
public class Application implements ApplicationRunner {

private static long updateInterval;
private static String fileExt;
private static String[] scripts;
private static String[] files;

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

@Autowired
FileWatcher fileWatcher;

public static void main(String[] args) {
Options options = new Options();
options.addOption(Option.builder("c").longOpt("script").hasArg().argName("script")
.desc("raw dsl script").build());
options.addOption(Option.builder("p").longOpt("port").hasArg().argName("port")
.desc("specify server port (default: 8080)").build());
options.addOption(Option.builder("n").longOpt("interval").hasArg().argName("interval")
.desc("specify update interval in seconds").build());
options.addOption(Option.builder().longOpt("ext").hasArg().argName("ext")
.desc("specify DSL file extension when the command arguments contains directory, (default: mir)").build());
options.addOption(Option.builder("h").longOpt("help")
.desc("print help message").build());

DefaultParser parser = new DefaultParser();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.err.println("Parsing failed: " + e.getMessage());
System.exit(1);
}

if (cmd.hasOption('h')) {
printUsage(options);
System.exit(1);
}

System.setProperty("server.port", cmd.getOptionValue('p', "8080"));

updateInterval = Long.parseLong(cmd.getOptionValue("n", "0"));
fileExt = cmd.getOptionValue("ext", "mir");
scripts = cmd.getOptionValues("c");
files = cmd.getArgs();

SpringApplication.run(Application.class, args);
}

private void watchWithFixedDelay(long delay) {
scheduler.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
fileWatcher.refreshPathSet();
}
}, delay, delay, TimeUnit.SECONDS);
}

@Override
public void run(ApplicationArguments args) throws IOException {
fileWatcher.setDslFileExtension(fileExt);
if (updateInterval > 0) {
watchWithFixedDelay(updateInterval);
}
if (files != null) {
for (String file : files) {
Path path = Paths.get(file);
fileWatcher.addFile(path);
}
}
if (scripts != null) {
for (String script : scripts) {
fileWatcher.addScript(script);
}
}
}

private static void printUsage(Options options) {
String header = "A web DSL to easily create a simple HTTP server\n\n";
String footer = "\nFor more information, see https://github.com/six-ddc/mirage";
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("mirage [-p <port>] [-c <script>] [file|dir]...", header, options, footer, false);
}
}
Loading

0 comments on commit 83137df

Please sign in to comment.