From a5a7aa81afa6097f1b84cc09319ada1df2384c34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9A=D0=B8=D1=80=D0=B8=D0=BB=D0=BB=20=D0=A1=D1=8B=D1=81?= =?UTF-8?q?=D0=BE=D0=B5=D0=B2?= Date: Sun, 15 Oct 2023 18:28:54 +0800 Subject: [PATCH] Makes golangling happy --- .golangci.yml | 4 +-- cmd/wsget/main.go | 5 +++- pkg/cli/cli.go | 61 ++++++++++++++++++++++------------------ pkg/cli/history.go | 15 ++++++---- pkg/formater/formater.go | 18 ++++++------ pkg/formater/json.go | 16 +++++------ pkg/ws/ws.go | 15 +++++----- 7 files changed, 74 insertions(+), 60 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 0efc0f6..c916cdd 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -25,7 +25,6 @@ linters: disable-all: true enable: - bodyclose - - deadcode - dogsled - dupl - errcheck @@ -48,14 +47,13 @@ linters: - predeclared - revive - staticcheck - - structcheck - stylecheck - thelper - tparallel - typecheck - unconvert - unparam - - varcheck + - unused - whitespace - wsl diff --git a/cmd/wsget/main.go b/cmd/wsget/main.go index a4667e9..573ca3d 100644 --- a/cmd/wsget/main.go +++ b/cmd/wsget/main.go @@ -31,6 +31,7 @@ func init() { if outputFile != nil && *outputFile != "" { var err error + OutputFH, err = os.Create(*outputFile) if err != nil { log.Fatal(err) @@ -40,10 +41,12 @@ func init() { func main() { fmt.Println("Connecting to", wsURL, "...") + wsInsp, err := ws.NewWS(wsURL) if err != nil { log.Fatal(err) } + defer wsInsp.Close() fmt.Println("Connected") @@ -64,6 +67,6 @@ func main() { err = client.Run(OutputFH) if err != nil { - log.Fatal(err) + log.Println("Error:", err) } } diff --git a/pkg/cli/cli.go b/pkg/cli/cli.go index 3ae1ee0..31e4a8b 100644 --- a/pkg/cli/cli.go +++ b/pkg/cli/cli.go @@ -13,33 +13,34 @@ import ( ) const ( - LINE_UP = "\033[1A" - LINE_CLEAR = "\x1b[2K" + LineUp = "\033[1A" + LineClear = "\x1b[2K" - HISTORY_FILE = ".wsget_history" - HISTORY_LIMIT = 100 + HistoryFilename = ".wsget_history" + HistoryLimit = 100 - MACOS_DELETE_KEY = 127 + MacOSDeleteKey = 127 - KEYBOARD_BUFFER_SIZE = 10 + KeyboardBufferSize = 10 ) type CLI struct { formater *formater.Formater history *History - wsConn *ws.WSConnection + wsConn *ws.Connection } -func NewCLI(wsConn *ws.WSConnection) *CLI { +func NewCLI(wsConn *ws.Connection) *CLI { currentUser, err := user.Current() if err != nil { log.Fatal(err) } + homeDir := currentUser.HomeDir return &CLI{ formater: formater.NewFormatter(), - history: NewHistory(homeDir+"/"+HISTORY_FILE, HISTORY_LIMIT), + history: NewHistory(homeDir+"/"+HistoryFilename, HistoryLimit), wsConn: wsConn, } } @@ -49,9 +50,14 @@ func (c *CLI) Run(outputFile *os.File) error { return err } defer keyboard.Close() - defer c.history.SaveToFile() + defer func() { + err := c.history.SaveToFile() + if err != nil { + fmt.Println("Fail to save history:", err) + } + }() - keysEvents, err := keyboard.GetKeys(KEYBOARD_BUFFER_SIZE) + keysEvents, err := keyboard.GetKeys(KeyboardBufferSize) if err != nil { return err } @@ -61,15 +67,14 @@ func (c *CLI) Run(outputFile *os.File) error { for { select { case event := <-keysEvents: - //nolint:gomnd switch event.Key { case keyboard.KeyCtrlC, keyboard.KeyCtrlD: return nil case keyboard.KeyEsc: fmt.Println("Request Mode: Type your API request and press Ctrl+S to send it. Press ESC to cancel request") - req, err := c.requestMode(keysEvents) + req, err := c.requestMode(keysEvents) if err != nil { if err.Error() == "interrupted" { return nil @@ -91,7 +96,6 @@ func (c *CLI) Run(outputFile *os.File) error { } case msg := <-c.wsConn.Messages: - output, err := c.formater.FormatMessage(msg) if err != nil { log.Printf("Fail to format message: %s, %s\n", err, msg.Data) @@ -104,6 +108,7 @@ func (c *CLI) Run(outputFile *os.File) error { if err != nil { log.Printf("Fail to format message for file: %s, %s\n", err, msg.Data) } + fmt.Fprintln(outputFile, output) } } @@ -120,7 +125,6 @@ func (c *CLI) requestMode(keyStream <-chan keyboard.KeyEvent) (string, error) { return buffer, e.Err } - //nolint:gomnd switch e.Key { case keyboard.KeyCtrlC, keyboard.KeyCtrlD: return buffer, fmt.Errorf("interrupted") @@ -128,42 +132,45 @@ func (c *CLI) requestMode(keyStream <-chan keyboard.KeyEvent) (string, error) { if buffer == "" { return buffer, fmt.Errorf("cannot send empty request") } + requet := strings.TrimSpace(buffer) + c.history.AddRequest(requet) + return requet, nil case keyboard.KeyEsc: return "", nil case keyboard.KeySpace: fmt.Print(" ") - buffer += " " - continue + buffer += " " case keyboard.KeyEnter: fmt.Print("\n") - buffer += "\n" - continue - case keyboard.KeyBackspace, keyboard.KeyDelete, MACOS_DELETE_KEY: - if len(buffer) == 0 { + buffer += "\n" + case keyboard.KeyBackspace, keyboard.KeyDelete, MacOSDeleteKey: + if buffer == "" { continue } if buffer[len(buffer)-1] == '\n' { buffer = buffer[:len(buffer)-1] - fmt.Print(LINE_UP) + + fmt.Print(LineUp) + startPrevLine := strings.LastIndex(buffer, "\n") if startPrevLine == -1 { startPrevLine = 0 } else { startPrevLine++ } + fmt.Print(buffer[startPrevLine:]) } else { fmt.Print("\b \b") buffer = buffer[:len(buffer)-1] } - continue case keyboard.KeyArrowUp: historyIndex++ req := c.history.GetRequst(historyIndex) @@ -177,7 +184,6 @@ func (c *CLI) requestMode(keyStream <-chan keyboard.KeyEvent) (string, error) { fmt.Print(req) buffer = req - continue case keyboard.KeyArrowDown: historyIndex-- req := c.history.GetRequst(historyIndex) @@ -191,12 +197,13 @@ func (c *CLI) requestMode(keyStream <-chan keyboard.KeyEvent) (string, error) { fmt.Print(req) buffer = req - continue default: if e.Key > 0 { continue } + fmt.Print(string(e.Rune)) + buffer += string(e.Rune) } } @@ -207,8 +214,8 @@ func (c *CLI) requestMode(keyStream <-chan keyboard.KeyEvent) (string, error) { func (c *CLI) clearInput(buffer string) { for i := 0; i < len(buffer); i++ { if buffer[i] == '\n' { - fmt.Print(LINE_UP) - fmt.Print(LINE_CLEAR) + fmt.Print(LineUp) + fmt.Print(LineClear) } else { fmt.Print("\b \b") } diff --git a/pkg/cli/history.go b/pkg/cli/history.go index 0e61036..fa0f2f4 100644 --- a/pkg/cli/history.go +++ b/pkg/cli/history.go @@ -7,9 +7,13 @@ import ( "strings" ) +const ( + HistoryFileRigths = 0o644 +) + type History struct { - requests []string fileName string + requests []string limit uint } @@ -20,13 +24,13 @@ func NewHistory(fileName string, limit uint) *History { requests: make([]string, 0), } - h.loadFromFile() + _ = h.loadFromFile() return h } func (h *History) loadFromFile() error { - fileHandler, err := os.OpenFile(h.fileName, os.O_RDONLY|os.O_CREATE, 0644) + fileHandler, err := os.OpenFile(h.fileName, os.O_RDONLY|os.O_CREATE, HistoryFileRigths) if err != nil { log.Println("Error opening history file:", err) return err @@ -57,9 +61,8 @@ func (h *History) loadFromFile() error { } func (h *History) SaveToFile() error { - fileHandler, err := os.OpenFile(h.fileName, os.O_WRONLY|os.O_CREATE, 0644) + fileHandler, err := os.OpenFile(h.fileName, os.O_WRONLY|os.O_CREATE, HistoryFileRigths) if err != nil { - log.Println("Error opening history file:", err) return err } @@ -79,7 +82,9 @@ func (h *History) SaveToFile() error { if request == "" { continue } + request = strings.ReplaceAll(request, "\n", "\\n") + _, err := writer.WriteString(request + "\n") if err != nil { return err diff --git a/pkg/formater/formater.go b/pkg/formater/formater.go index af0ce81..f8c6356 100644 --- a/pkg/formater/formater.go +++ b/pkg/formater/formater.go @@ -10,14 +10,14 @@ import ( // Formater is a struct that contains two formatters, one for text and one for JSON. type Formater struct { text *TextFormater - json *JsonFormater + json *JSONFormater } // NewFormatter creates a new instance of Formater struct. func NewFormatter() *Formater { return &Formater{ text: NewTextFormater(), - json: NewJsonFormater(), + json: NewJSONFormater(), } } @@ -27,13 +27,13 @@ func NewFormatter() *Formater { func (f *Formater) FormatMessage(wsMsg ws.Message) (string, error) { wsMsgData := wsMsg.Data - obj, ok := f.parseJson(wsMsgData) + obj, ok := f.parseJSON(wsMsgData) if !ok { return f.formatTestMessage(wsMsg.Type, wsMsgData) } - return f.formatJsonMessage(wsMsg.Type, obj) + return f.formatJSONMessage(wsMsg.Type, obj) } // FormatForFile formats the given WebSocket message for a file. @@ -42,7 +42,7 @@ func (f *Formater) FormatMessage(wsMsg ws.Message) (string, error) { func (f *Formater) FormatForFile(wsMsg ws.Message) (string, error) { wsMsgData := wsMsg.Data - obj, ok := f.parseJson(wsMsgData) + obj, ok := f.parseJSON(wsMsgData) if !ok { return f.text.FormatForFile(wsMsgData) @@ -65,8 +65,8 @@ func (f *Formater) formatTestMessage(msgType ws.MessageType, data string) (strin } } -// formatJsonMessage formats the given WebSocket message data as JSON based on its type. -func (f *Formater) formatJsonMessage(msgType ws.MessageType, data any) (string, error) { +// formatJSONMessage formats the given WebSocket message data as JSON based on its type. +func (f *Formater) formatJSONMessage(msgType ws.MessageType, data any) (string, error) { switch msgType { case ws.Request: return f.json.FormatRequest(data) @@ -79,9 +79,9 @@ func (f *Formater) formatJsonMessage(msgType ws.MessageType, data any) (string, } } -// parseJson parses the given string as JSON and returns the parsed object. +// parseJSON parses the given string as JSON and returns the parsed object. // If the string is not a valid JSON, it returns false as the second value. -func (f *Formater) parseJson(data string) (any, bool) { +func (f *Formater) parseJSON(data string) (any, bool) { var obj any err := json.Unmarshal([]byte(data), &obj) diff --git a/pkg/formater/json.go b/pkg/formater/json.go index 63651bf..ffe7ed7 100644 --- a/pkg/formater/json.go +++ b/pkg/formater/json.go @@ -7,14 +7,14 @@ import ( "github.com/fatih/color" ) -// JsonFormater is a struct that contains two colorjson formatters for request and response. -type JsonFormater struct { +// JSONFormater is a struct that contains two colorjson formatters for request and response. +type JSONFormater struct { request *colorjson.Formatter response *colorjson.Formatter } -// NewJsonFormater creates a new instance of JsonFormater and returns a pointer to it. -func NewJsonFormater() *JsonFormater { +// NewJSONFormater creates a new instance of JSONFormater and returns a pointer to it. +func NewJSONFormater() *JSONFormater { request := colorjson.NewFormatter() request.Indent = 2 request.KeyColor = color.New(color.FgMagenta) @@ -31,14 +31,14 @@ func NewJsonFormater() *JsonFormater { response.NumberColor = color.New(color.FgGreen) response.NullColor = color.New(color.FgRed) - return &JsonFormater{ + return &JSONFormater{ request: request, response: response, } } // FormatRequest formats the given data as a JSON string using the request formatter. -func (jf *JsonFormater) FormatRequest(data any) (string, error) { +func (jf *JSONFormater) FormatRequest(data any) (string, error) { output, err := jf.request.Marshal(data) if err != nil { return "", err @@ -48,7 +48,7 @@ func (jf *JsonFormater) FormatRequest(data any) (string, error) { } // FormatResponse formats the given data as a JSON string using the response formatter. -func (jf *JsonFormater) FormatResponse(data any) (string, error) { +func (jf *JSONFormater) FormatResponse(data any) (string, error) { output, err := jf.response.Marshal(data) if err != nil { return "", err @@ -58,7 +58,7 @@ func (jf *JsonFormater) FormatResponse(data any) (string, error) { } // FormatForFile formats the given data as a JSON string using the default json package. -func (jf *JsonFormater) FormatForFile(data any) (string, error) { +func (jf *JSONFormater) FormatForFile(data any) (string, error) { output, err := json.Marshal(data) if err != nil { return "", err diff --git a/pkg/ws/ws.go b/pkg/ws/ws.go index 0b5baf6..ef4d358 100644 --- a/pkg/ws/ws.go +++ b/pkg/ws/ws.go @@ -15,7 +15,7 @@ const ( ) const ( - WS_MESSAGE_BUFFER_SIZE = 100 + WSMessageBufferSize = 100 ) type Message struct { @@ -23,23 +23,24 @@ type Message struct { Type MessageType `json:"type"` } -type WSConnection struct { +type Connection struct { ws *websocket.Conn Messages chan Message } -func NewWS(url string) (*WSConnection, error) { +func NewWS(url string) (*Connection, error) { ws, err := websocket.Dial(url, "", "http://localhost") if err != nil { return nil, err } - messages := make(chan Message, WS_MESSAGE_BUFFER_SIZE) + messages := make(chan Message, WSMessageBufferSize) go func(messages chan Message) { for { var msg string + err = websocket.Message.Receive(ws, &msg) if err != nil { log.Fatal("Fail to read from WS connection:", err) @@ -49,10 +50,10 @@ func NewWS(url string) (*WSConnection, error) { } }(messages) - return &WSConnection{ws: ws, Messages: messages}, nil + return &Connection{ws: ws, Messages: messages}, nil } -func (wsInsp *WSConnection) Send(msg string) error { +func (wsInsp *Connection) Send(msg string) error { err := websocket.Message.Send(wsInsp.ws, msg) if err != nil { @@ -64,6 +65,6 @@ func (wsInsp *WSConnection) Send(msg string) error { return nil } -func (wsInsp *WSConnection) Close() { +func (wsInsp *Connection) Close() { wsInsp.ws.Close() }