From e289d8194267b14b0f1c1299ffb6fa461917dc48 Mon Sep 17 00:00:00 2001 From: Shingo Kawamura Date: Sun, 9 Jul 2017 12:05:18 +0900 Subject: [PATCH] Add logger.go --- MIT-LICENSE | 19 ++++++++++++++++ api/api.go | 59 ++++++++++++++++++++++++++++++++++++++++++++---- cmd/cmd.go | 21 ++++++++--------- config/config.go | 16 ++++++------- logger/logger.go | 25 ++++++++++++++++++++ main.go | 27 ++++++++-------------- 6 files changed, 124 insertions(+), 43 deletions(-) create mode 100644 MIT-LICENSE create mode 100644 logger/logger.go diff --git a/MIT-LICENSE b/MIT-LICENSE new file mode 100644 index 0000000..3151dff --- /dev/null +++ b/MIT-LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2017 Shingo Kawamura + +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. diff --git a/api/api.go b/api/api.go index 0e3aba3..0008a53 100644 --- a/api/api.go +++ b/api/api.go @@ -1,11 +1,60 @@ package api -type Response struct { - Host string `json:Host` +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "os/user" + "path/filepath" + "time" + + "github.com/blp1526/scv/config" + "github.com/blp1526/scv/logger" +) + +type Body struct { + Host string `json:"Host"` Password string `json:"Password"` - Port string `json:Port` + Port string `json:"Port"` } -func Request(zoneName string, ServerId string) (*Response, err) { - return response, err +func Request(body interface{}, zoneName string, serverId string) error { + client := &http.Client{Timeout: 10 * time.Second} + + scheme := "https" + host := "secure.sakura.ad.jp" + path := "/cloud/zone/" + zoneName + "/api/cloud/1.1/server/" + serverId + "/vnc/proxy" + url := scheme + "://" + host + path + logger.Debug("URL is " + url) + + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return err + } + + scv := &config.Scv{} + current, _ := user.Current() + dir := filepath.Join(current.HomeDir, "scv.json") + logger.Debug(dir) + config.Load(scv, dir) + + if scv.AccessToken == "" || scv.AccessTokenSecret == "" { + message := fmt.Sprintf("Check scv.json, AccessToken is %s, AccessTokenSecret is %s", scv.AccessToken, scv.AccessTokenSecret) + return errors.New(message) + } + + req.SetBasicAuth(scv.AccessToken, scv.AccessTokenSecret) + resp, err := client.Do(req) + if err != nil { + return err + } + // NOTE: not 200 + if resp.StatusCode != 201 { + message := fmt.Sprintf("Bad response status (got %d, expected 201)", resp.StatusCode) + return errors.New(message) + } + + defer resp.Body.Close() + return json.NewDecoder(resp.Body).Decode(body) } diff --git a/cmd/cmd.go b/cmd/cmd.go index 3f97033..f07b10f 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -1,26 +1,23 @@ package cmd import ( - "fmt" "os/exec" "github.com/blp1526/scv/api" ) func Run(zoneName string, serverName string) error { - apiResponse, err := api.Request(zoneName, serverId) - vncPath = cmd.vncPath(apiResponse) - err := exec.Command("open", vncPath).Run() - + body := &api.Body{} + err := api.Request(body, zoneName, serverName) if err != nil { - fmt.Println(err) + return err } -} -func vncPath(apiResponse) string { - password = "" - host = "" - port = "" + vncPath := vncPath(*body) + err = exec.Command("open", vncPath).Run() + return err +} - return "// vnc://:%s@%s:%s" + password + host + port +func vncPath(body api.Body) string { + return "// vnc://:" + body.Password + "@" + body.Host + ":" + body.Port } diff --git a/config/config.go b/config/config.go index dbcad32..a5af231 100644 --- a/config/config.go +++ b/config/config.go @@ -7,8 +7,8 @@ import ( type Scv struct { AccessToken string `json:"access_token"` - AccessTokenSecret string `json:access_token_secret` - Servers []Server `json:servers` + AccessTokenSecret string `json:"access_token_secret"` + Servers []Server `json:"servers"` } type Server struct { @@ -17,17 +17,15 @@ type Server struct { ID string `json:"id"` } -func Load(filePath string) (*Scv, error) { - var scv Scv - +func Load(scv *Scv, filePath string) error { bytes, err := ioutil.ReadFile(filePath) if err != nil { - return &scv, err + return err } - err = json.Unmarshal(bytes, &scv) + err = json.Unmarshal(bytes, scv) if err != nil { - return &scv, err + return err } - return &scv, err + return err } diff --git a/logger/logger.go b/logger/logger.go new file mode 100644 index 0000000..35129fa --- /dev/null +++ b/logger/logger.go @@ -0,0 +1,25 @@ +package logger + +import ( + "fmt" + "os" +) + +const normal = "\033[m" +const black = "\033[30m" +const red = "\033[31m" +const green = "\033[32m" +const yellow = "\033[33m" +const blue = "\033[34m" +const magenta = "\033[35m" +const cyan = "\033[36m" +const lightGray = "\033[37m" + +func Debug(message string) { + fmt.Printf("%sdebug%s: %s\n", lightGray, normal, message) +} + +func Fatal(message string) { + fmt.Printf("%sfatal%s: %s\n", red, normal, message) + os.Exit(1) +} diff --git a/main.go b/main.go index b7c41a1..c4ae46c 100644 --- a/main.go +++ b/main.go @@ -1,11 +1,3 @@ -// This app's binary is MacOS only. -// -// * Open $HOME/scv.json -// * then get Web API ACCESS_TOKEN and ACCESS_TOKEN_SECRET -// * then convert os.Args[1] to Web API :id -// * Request "GET /somewhere/:id", then get response as JSON format -// * Make "open command argument" from JSON -// * Run MacOS command "open argument" package main import ( @@ -13,23 +5,24 @@ import ( "os" "github.com/blp1526/scv/cmd" + "github.com/blp1526/scv/logger" ) -func main() { - version := "0.0.1" - expectedArgsSize := 2 +const version = "0.0.1" +const expectedArgsSize = 2 +func main() { argsSize := len(os.Args) - 1 if argsSize == 0 { fmt.Printf("scv version %s\n", version) - } else if argsSize == 2 { - err := cmd.Run(os.Args[1], os.Args[2]) + } else if argsSize == expectedArgsSize { + zoneName := os.Args[1] + serverName := os.Args[2] + err := cmd.Run(zoneName, serverName) if err != nil { - fmt.Println(err) + logger.Fatal(fmt.Sprintf("%s", err)) } } else { - msg := "fatal: Wrong number of arguments (given %d, expected %d)\n" - fmt.Printf(msg, argsSize, expectedArgsSize) - os.Exit(1) + logger.Fatal(fmt.Sprintf("Expected arguments size is %d", expectedArgsSize)) } }