Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add kadai4/shiimaxx #62

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions kadai4/shiimaxx/omikuji-api/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib

# Test binary, build with `go test -c`
*.test

# Output of the go coverage tool, specifically when used with LiteIDE
*.out
21 changes: 21 additions & 0 deletions kadai4/shiimaxx/omikuji-api/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018 YOSHIMA Takatada

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.
40 changes: 40 additions & 0 deletions kadai4/shiimaxx/omikuji-api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# omikuji-api

omikuji-api responses result for omikuji.
The following are responses.

```
{"result_code":1,"result":"kyo"}
{"result_code":2,"result":"kichi"}
{"result_code":3,"result":"kichi"}
{"result_code":4,"result":"chukichi"}
{"result_code":5,"result":"chukichi"}
{"result_code":6,"result":"daikichi"}
```

This is homework for gopherdojo.
See also: https://github.com/gopherdojo/dojo1/tree/master/kadai4

## Usage

```
omikuji-api [(-p | --port) port]
```

```
Usage of omikuji-api:
-p int
port number(Short) (default 8080)
-port int
port number (default 8080)
-version
print version information
```

## License

[MIT](https://github.com/shiimaxx/omikuji-api/blob/master/LICENSE)

## Author

[shiimaxx](https://github.com/shiimaxx)
93 changes: 93 additions & 0 deletions kadai4/shiimaxx/omikuji-api/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package main

import (
"encoding/json"
"log"
"math/rand"
"net/http"
"time"
"flag"
"fmt"
"os"
)


const (
// Exit codes are int values that represent an exit code for a particular error.
ExitCodeOK int = 0
ExitCodeError int = 1 + iota
// DefaultPort default for http server listen port
DefaultPort = 8080
)

var (
logger = log.New(os.Stdout, "logger: ", log.Lshortfile)
)

// OmikujiResponse omikuji-api response
type OmikujiResponse struct {
ResultCode int `json:"result_code"`
Result string `json:"result"`
}

var getTime = func() time.Time {
return time.Now()
}

func omikuji() (int, string) {
t := getTime()
if t.Month() == time.January && t.Day() >= 1 && t.Day() <= 3 {
return 0, "daikichi"
}
rand.Seed(t.UnixNano())
s := rand.Intn(6) + 1

switch s {
case 1:
return s, "kyo"
case 2, 3:
return s, "kichi"
case 4, 5:
return s, "chukichi"
case 6:
return s, "daikichi"
default:
return s, ""
}
}

// HandleOmikujiAPI omikuji api
func HandleOmikujiAPI(w http.ResponseWriter, r *http.Request) {
logger.Println("request: ", r.URL)
w.Header().Set("Content-Type", "application/json; charset=utf-8")

var v OmikujiResponse
v.ResultCode, v.Result = omikuji()

if err := json.NewEncoder(w).Encode(v); err != nil {
logger.Println("error:", err)
}
}

func main() {
var (
port int
version bool
)

flags := flag.NewFlagSet(Name, flag.ContinueOnError)
flags.IntVar(&port, "port", DefaultPort, "port number")
flags.IntVar(&port, "p", DefaultPort, "port number(Short)")
flags.BoolVar(&version, "version", false, "print version information")
if err := flags.Parse(os.Args[1:]); err != nil {
os.Exit(ExitCodeError)
}

if version {
fmt.Printf("%s version %s\n", Name, Version)
os.Exit(ExitCodeOK)
}

http.HandleFunc("/", HandleOmikujiAPI)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
}
44 changes: 44 additions & 0 deletions kadai4/shiimaxx/omikuji-api/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package main

import (
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)

func TestHandleOmikujiAPI(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", nil)
HandleOmikujiAPI(w, r)
rw := w.Result()
defer rw.Body.Close()

if rw.StatusCode != http.StatusOK {
t.Errorf("expected %d to eq %d", http.StatusOK, rw.StatusCode)
}
}

func TestHandleOmikujiAPIHappyNewYear(t *testing.T) {
getTime = func() time.Time { return time.Date(2018, time.January, 1, 0, 0, 0, 0, time.Local) }

w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", nil)
HandleOmikujiAPI(w, r)
rw := w.Result()
defer rw.Body.Close()

if rw.StatusCode != http.StatusOK {
t.Errorf("expected %d to eq %d", http.StatusOK, rw.StatusCode)
}

b, _ := ioutil.ReadAll(rw.Body)
actual := string(b)
expected := "{\"result_code\":0,\"result\":\"daikichi\"}"

if !strings.Contains(actual, expected) {
t.Errorf("expected %s to eq %s", expected, actual)
}
}
7 changes: 7 additions & 0 deletions kadai4/shiimaxx/omikuji-api/version.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package main

// Name is the application name
const Name string = "omikuji-api"

// Version is the application version
const Version string = "0.1.0"