Skip to content

Commit

Permalink
create API
Browse files Browse the repository at this point in the history
  • Loading branch information
takumism committed Aug 14, 2019
1 parent ba760d0 commit a12a96e
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
41 changes: 41 additions & 0 deletions app/controllers/webserver.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package controllers

import (
"encoding/json"
"fmt"
"github.com/taqboz/gotello/config"
"html/template"
"log"
"net/http"
"regexp"
)

// テンプレートの読み込み
Expand All @@ -28,9 +31,47 @@ func viewControllerHandler(w http.ResponseWriter, r *http.Request) {
}
}

// 以下APIの処理
type APIResult struct {
Result interface{} `json:"result"`
Code int `json:"code"`
}

func APIResponse(w http.ResponseWriter, result interface{}, code int) {
res := APIResult{Result: result, Code: code}
js, err := json.Marshal(res)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(js)
}

var apiValidPath = regexp.MustCompile("^/api/(command|shake|video)")

func apiMakeHandler(fn func(w http.ResponseWriter, r *http.Request)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
m := apiValidPath.FindStringSubmatch(r.URL.Path)
if len(m) == 0 {
// TODO
return
}
fn(w, r)
}
}

func apiCommandHandler(w http.ResponseWriter, r *http.Request) {
command := r.FormValue("command")
log.Printf("action=apiCommandHandler command=%s", command)
APIResponse(w, "OK", http.StatusOK)
}

func StartWebServer() error {
http.HandleFunc("/", viewIndexHandler)
http.HandleFunc("/controller/", viewControllerHandler)
http.HandleFunc("/api/command/", apiMakeHandler(apiCommandHandler))
// "static"をファイルサーバーとして使用する
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
return http.ListenAndServe(fmt.Sprintf("%s:%d", config.Config.Address, config.Config.Port), nil)
Expand Down
2 changes: 2 additions & 0 deletions gotello.log
Original file line number Diff line number Diff line change
Expand Up @@ -471,3 +471,5 @@ created by net/http.(*Server).Serve
/usr/local/Cellar/go/1.12.7/libexec/src/net/http/server.go:2884 +0x2f4
2019/08/14 11:28:18 main.go:12: listen tcp 0.0.0.0:8080: bind: address already in use
2019/08/14 11:28:38 webserver.go:15: open app/view/index.html: no such file or directory
2019/08/14 13:40:01 webserver.go:67: action=apiCommandHandler command=ceaseRotation
2019/08/14 13:40:02 webserver.go:67: action=apiCommandHandler command=takeOff

0 comments on commit a12a96e

Please sign in to comment.