Skip to content

Instantly share code, notes, and snippets.

@nobuhito nobuhito/MockSwitch.go
Last active Aug 29, 2015

Embed
What would you like to do?
JavascriptとStylesheet(ついでにMarkdown)だけでモックを作れるWebサーバー

MockSwitch.go

Qiita

Usage

go build MockSwitch.go
mkdir hoge
echo "document.body.appendChild(document.createTextNode('Hello MockSwitch'));" > hoge/hoge.js
./MockSwitch

Browse http://localhost:8000/hoge

Tree example

└ MockSwitch.go
└ MockSwitch(\.exe)?
└ hoge
│ └ 0-util.js
│ └ hoge.css
│ └ hoge.js
│ └ hoge.md
└ dist
  └ bootstrap
  │ └ 0-bootstrap.min.css
  │ └ 1-bootstrap-theme.css
  │ └ bootstrap.min.js
  └ d3.v3.min.js
package main
import (
"github.com/zenazn/goji"
"github.com/zenazn/goji/web"
"github.com/google/go-github/github"
"net/http"
"fmt"
"regexp"
"io/ioutil"
"path/filepath"
"os"
"strings"
)
func route(m *web.Mux) {
faviconPattern := regexp.MustCompile("^(.*\\.ico)$")
m.Get(faviconPattern, http.FileServer(http.Dir("./")))
m.Get("/:id", render)
assetsPattern := regexp.MustCompile("^/(.*/.*)$")
m.Get(assetsPattern, http.FileServer(http.Dir("./")))
}
func main() {
route(goji.DefaultMux)
goji.Serve()
}
func getFileLIst(dir, prefix string) (list []string) {
err := filepath.Walk(dir,
func(path string, info os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return err
}
if info.IsDir() {
return nil
}
pos := strings.LastIndex(path, ".")
if path[pos:] == "." + prefix {
list = append(list, strings.Join(strings.Split(path, "\\"), "/"))
}
return nil
})
if err != nil {
fmt.Println(err);
}
return list
}
func render(c web.C, w http.ResponseWriter, r *http.Request) {
id := c.URLParams["id"]
assets := []string{"css", "js", "md", "html"}
files := map[string] []string{}
for i := range assets {
list := []string{}
asset := assets[i]
list = append(list, getFileLIst("./dist", asset)...)
list = append(list, getFileLIst("./" + id, asset)...)
files[asset] = list
}
css := ""
for _, v := range files["css"] {
css += "<link rel=\"stylesheet\" href=\"/" + v + "\">\n"
}
js := ""
for _, v := range files["js"] {
js += "<script src=\"/" + v + "\"></script>\n"
}
md := ""
for _, v := range files["md"] {
text, err := ioutil.ReadFile(v);
if (err == nil) {
client := github.NewClient(nil)
mhtml, _, err := client.Markdown(string(text), nil)
if (err == nil) {
md += mhtml + "\n"
}
}
}
html := ""
for _, v := range files["html"] {
text, err := ioutil.ReadFile(v);
if err == nil {
html += string(text) + "\n"
}
}
ret := `
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
%s
</head>
<body class="container">
%s
%s
%s
</body>
`
fmt.Fprintf(w, ret, css, html, md, js)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.