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

tmp #7

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
3 changes: 3 additions & 0 deletions 03/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
FROM mysql:5.7
EXPOSE 3306
CMD ["mysqld"]
43 changes: 43 additions & 0 deletions 03/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
run:
go build -o build . && ./build

test:
export HTTPDOC=1 && go test -v ./...

docker-build:
docker-compose build

docker-up:
docker-compose up -d

docker-stop:
docker-compose stop

docker-rm:
docker-compose rm

docker-ssh:
docker exec -it goapi /bin/bash

docker-server: docker-build docker-up

docker-clean: docker-stop docker-rm

config-set:
cp -i db.yml.tmpl db.yml

host:=http://localhost:8080
auth:=admin
token:=token

curl-auth-login:
curl $(host)/api/auth/login?token=$(token)

curl-members-id:
curl -H 'Authorization:$(auth)' $(host)/api/members/$(id)

curl-members:
curl -H 'Authorization:$(auth)' $(host)/api/members

curl-reqid:
curl -H 'Authorization:$(auth)' -H 'X-Request-ID:test' $(host)/api/members
56 changes: 56 additions & 0 deletions 03/controller.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package main

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

"github.com/go-chi/chi"
)

// Controller ハンドラ用
type Controller struct {
}

// NewController コンストラクタ
func NewController() *Controller {
return &Controller{}
}

// User user
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}

// Show endpoint
func (c *Controller) Show(w http.ResponseWriter, r *http.Request) (int, interface{}, error) {
id, _ := strconv.Atoi(chi.URLParam(r, "id"))
res := User{ID: id, Name: fmt.Sprint("name_", id)}
return http.StatusOK, res, nil
}

// List endpoint
func (c *Controller) List(w http.ResponseWriter, r *http.Request) (int, interface{}, error) {
users := []User{
{1, "hoge"},
{2, "foo"},
{3, "bar"},
}
return http.StatusOK, users, nil
}

// AuthInfo 何らかの認証後にトークン発行するようなもの
type AuthInfo struct {
Authorization string `json:"authorization"`
}

// Login endpoint
func (c *Controller) Login(w http.ResponseWriter, r *http.Request) (int, interface{}, error) {
token := r.URL.Query().Get("token")
if token != "token" {
return http.StatusUnauthorized, nil, fmt.Errorf("有効でないトークンです: %s", token)
}
res := AuthInfo{Authorization: "admin"}
return http.StatusOK, res, nil
}
63 changes: 63 additions & 0 deletions 03/db.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package main

import (
"io"
"io/ioutil"
"os"

"github.com/jmoiron/sqlx"
"gopkg.in/yaml.v1"
// MySQL driver
_ "github.com/go-sql-driver/mysql"
)

// Configs 環境ごとの設定情報をもつ
type Configs map[string]*Config

// Open 指定された環境についてDBに接続します。
func (cs Configs) Open(env string) (*sqlx.DB, error) {
config, ok := cs[env]
if !ok {
return nil, nil
}
return config.Open()
}

// Config sql-migrateの設定ファイルと同じ形式を想定している
type Config struct {
Datasource string `yaml:"datasource"`
}

// DSN 設定されているDSNを返します
func (c *Config) DSN() string {
return c.Datasource
}

// Open Configで指定されている接続先に接続する。
// MySQL固定
func (c *Config) Open() (*sqlx.DB, error) {
return sqlx.Open("mysql", c.DSN())
}

// NewConfigsFromFile Configから設定を読み取る
func NewConfigsFromFile(path string) (Configs, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close() // nolint: errcheck
return NewConfigs(f)
}

// NewConfigs io.ReaderからDB用設定を読み取る
func NewConfigs(r io.Reader) (Configs, error) {
b, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
var configs Configs
if err = yaml.Unmarshal(b, &configs); err != nil {
return nil, err
}
return configs, nil
}
25 changes: 25 additions & 0 deletions 03/db.yml.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Example Database Configurationgorp
#
# For using gorp, enable parseTime option on MySQL to serialize/deserialize time.Time.
#
# see: https://github.com/rubenv/sql-migrate/issues/2
#
# Also interpolateParams=true, to replace placement on database server.
#
# see: https://github.com/go-sql-driver/mysql/pull/309
# see: http://dsas.blog.klab.org/archives/52191467.html
develop:
dialect: mysql
datasource: go-chi:password@tcp(localhost:3306)/go-chi?parseTime=true&collation=utf8mb4_general_ci&interpolateParams=true&loc=UTC
dir: mysql/migrations

staging:
dialect: mysql
datasource: go-chi:password@tcp(localhost:3306)/go-chi?parseTime=true&collation=utf8mb4_general_ci&interpolateParams=true&loc=UTC
dir: mysql/migrations

production:
dialect: mysql
datasource: go-chi:password@tcp(localhost:3306)/go-chi?parseTime=true&collation=utf8mb4_general_ci&interpolateParams=true&loc=UTC
dir: mysql/migrations

25 changes: 25 additions & 0 deletions 03/db_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package main

import (
"strings"
"testing"

"github.com/stretchr/testify/assert"
)

func TestReadConfig(t *testing.T) {
assert := assert.New(t)
r := strings.NewReader(`
development:
datasource: root@localhost/dev

test:
datasource: root@localhost/test
`)

configs, err := NewConfigs(r)
assert.NoError(err)
c, ok := configs["development"]
assert.True(ok)
assert.Equal("root@localhost/dev", c.DSN(), "they should be equal")
}
54 changes: 54 additions & 0 deletions 03/doc/doc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# github.com/pei0804/go-chi-api-example

generated docs.

## Routes

<details>
<summary>`/api/*/members/*`</summary>

- [github.com/go-chi/cors.(*Cors).Handler-fm](/03/main.go#L49)
- [RequestIDHandler](https://github.com/ascarter/requestid/requestid.go#L28)
- [CloseNotify](https://github.com/go-chi/chi/middleware/closenotify18.go#L16)
- [main.loggingMiddleware](/03/middleware.go#L28)
- [Timeout.func1](https://github.com/go-chi/chi/middleware/timeout.go#L33)
- **/api/***
- [main.Auth.func1](/03/middleware.go#L15)
- **/members/***
- **/**
- _GET_
- [main.(handler).ServeHTTP-fm](/03/main.go#L62)

</details>
<details>
<summary>`/api/*/members/*/{id}`</summary>

- [github.com/go-chi/cors.(*Cors).Handler-fm](/03/main.go#L49)
- [RequestIDHandler](https://github.com/ascarter/requestid/requestid.go#L28)
- [CloseNotify](https://github.com/go-chi/chi/middleware/closenotify18.go#L16)
- [main.loggingMiddleware](/03/middleware.go#L28)
- [Timeout.func1](https://github.com/go-chi/chi/middleware/timeout.go#L33)
- **/api/***
- [main.Auth.func1](/03/middleware.go#L15)
- **/members/***
- **/{id}**
- _GET_
- [main.(handler).ServeHTTP-fm](/03/main.go#L62)

</details>
<details>
<summary>`/api/auth/*/login`</summary>

- [github.com/go-chi/cors.(*Cors).Handler-fm](/03/main.go#L49)
- [RequestIDHandler](https://github.com/ascarter/requestid/requestid.go#L28)
- [CloseNotify](https://github.com/go-chi/chi/middleware/closenotify18.go#L16)
- [main.loggingMiddleware](/03/middleware.go#L28)
- [Timeout.func1](https://github.com/go-chi/chi/middleware/timeout.go#L33)
- **/api/auth/***
- **/login**
- _GET_
- [main.(handler).ServeHTTP-fm](/03/main.go#L62)

</details>

Total # of routes: 3
69 changes: 69 additions & 0 deletions 03/doc/list.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# API doc

This is API documentation for List Controller. This is generated by `httpdoc`. Don't edit by hand.

## Table of contents

- [[200] GET /api/members](#200-get-apimembers)


## [200] GET /api/members

get user list

### Request



Headers

| Name | Value | Description |
| ----- | :----- | :--------- |
| Accept-Encoding | gzip | |
| Authorization | admin | auth token |
| User-Agent | Go-http-client/1.1 | |







### Response

Headers

| Name | Value | Description |
| ----- | :----- | :--------- |
| Content-Type | application/json | |





Response example

<details>
<summary>Click to expand code.</summary>

```javascript
[
{
"id": 1,
"name": "hoge"
},
{
"id": 2,
"name": "foo"
},
{
"id": 3,
"name": "bar"
}
]
```

</details>



Loading