Skip to content

Commit

Permalink
Add web API (fix #17)
Browse files Browse the repository at this point in the history
  • Loading branch information
moul committed Jun 11, 2017
1 parent 074c790 commit 685962c
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 4 deletions.
8 changes: 4 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
NAME = number-to-words
PACKAGES = $(notdir $(wildcard ./cmd/*))
SOURCE := $(shell find . -name "*.go")


all: build


$(NAME): $(SOURCE)
go build -o ./$(NAME) ./cmd/$(NAME)/main.go
$(PACKAGES): $(SOURCE)
go install -v ./cmd/$@


.PHONY: build
build: $(NAME)
build: $(PACKAGES)


.PHONY: docker
Expand Down
77 changes: 77 additions & 0 deletions cmd/ntw-web/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package main

import (
"fmt"
"net/http"
"os"
"path"
"strconv"

"github.com/apex/log"
"github.com/gorilla/mux"
"github.com/moul/number-to-words"
"github.com/urfave/cli"
)

func main() {
app := cli.NewApp()
app.Name = path.Base(os.Args[0])
app.Author = "Manfred Touron"
app.Email = "https://github.com/moul/number-to-words"
app.Version = ntw.Version
app.Usage = "number to number web API"

app.Flags = []cli.Flag{
cli.StringFlag{
Name: "bind, b",
Usage: "HTTP bind address",
Value: ":8000",
},
}
app.Action = server
app.Run(os.Args)
}

func server(c *cli.Context) error {
r := mux.NewRouter()
r.HandleFunc("/{lang}/{number}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)

number, err := strconv.Atoi(vars["number"])
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "invalid input number %q: %v\n", vars["number"], err)
return
}

var output string
switch vars["lang"] {
case "en", "english":
output = ntw.IntegerToEnglish(number)
case "fr", "french":
output = ntw.IntegerToFrench(number)
case "it", "italian":
output = ntw.IntegerToItalian(number)
case "es", "spanish":
output = ntw.IntegerToSpanish(number)
case "se", "swedish":
output = ntw.IntegerToSpanish(number)
case "nl", "dutch":
output = ntw.IntegerToSpanish(number)
case "roman":
output = ntw.IntegerToRoman(number)
case "roman-unicode":
output = ntw.IntegerToUnicodeRoman(number)
case "aegean":
output = ntw.IntegerToAegean(number)
default:
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "no such language %q\n", vars["lang"])
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "%s\n", output)
})
log.Infof("Listening to %s", c.String("bind"))
return http.ListenAndServe(c.String("bind"), r)
}

0 comments on commit 685962c

Please sign in to comment.