├── .circleci └── config.yml ├── .github ├── dependabot.yml └── workflows │ └── release.yml ├── .gitignore ├── .goreleaser.yaml ├── LICENSE ├── Makefile ├── README.rst ├── config.go ├── config_test.go ├── go.mod ├── go.sum ├── install.sh ├── main.go ├── mqtt.go ├── publish.go └── subscribe.go /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # Golang CircleCI 2.0 configuration file 2 | # 3 | # Check https://circleci.com/docs/2.0/language-go/ for more details 4 | version: 2 5 | jobs: 6 | build: 7 | docker: 8 | # specify the version 9 | - image: cimg/go:1.18.1 10 | 11 | #### TEMPLATE_NOTE: go expects specific checkout path representing url 12 | #### expecting it in the form of 13 | #### /go/src/github.com/circleci/go-tool 14 | #### /go/src/bitbucket.org/circleci/go-tool 15 | steps: 16 | - checkout 17 | 18 | # specify any bash command here prefixed with `run: ` 19 | - run: go get -v -t -d ./... 20 | - run: go test -v ./... 21 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: gomod 4 | directory: / 5 | schedule: 6 | interval: daily 7 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: goreleaser 2 | 3 | on: 4 | push: 5 | # run only against tags 6 | tags: 7 | - '*' 8 | 9 | permissions: 10 | contents: write 11 | # packages: write 12 | # issues: write 13 | 14 | jobs: 15 | goreleaser: 16 | runs-on: ubuntu-latest 17 | steps: 18 | - 19 | name: Checkout 20 | uses: actions/checkout@v2 21 | with: 22 | fetch-depth: 0 23 | - 24 | name: Fetch all tags 25 | run: git fetch --force --tags 26 | - 27 | name: Set up Go 28 | uses: actions/setup-go@v2 29 | with: 30 | go-version: 1.18 31 | - 32 | name: Run GoReleaser 33 | uses: goreleaser/goreleaser-action@v2 34 | with: 35 | distribution: goreleaser 36 | version: latest 37 | args: release --rm-dist 38 | env: 39 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 40 | 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | vendor/ 2 | build/ 3 | -------------------------------------------------------------------------------- /.goreleaser.yaml: -------------------------------------------------------------------------------- 1 | before: 2 | hooks: 3 | - go mod tidy 4 | builds: 5 | - env: 6 | - CGO_ENABLED=0 7 | goos: 8 | - linux 9 | - windows 10 | - darwin 11 | - freebsd 12 | - netbsd 13 | - openbsd 14 | goarch: 15 | - 386 16 | - amd64 17 | - arm64 18 | goarm: 19 | - 6 20 | - 7 21 | ignore: 22 | - goos: darwin 23 | goarch: 386 24 | # - goos: windows 25 | # goarch: arm64 26 | archives: 27 | - format: binary 28 | name_template: '{{ .Binary }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}' 29 | files: 30 | - mqttcli_* 31 | format_overrides: 32 | - goos: windows 33 | format: zip 34 | changelog: 35 | sort: asc 36 | filters: 37 | exclude: 38 | - '^docs:' 39 | - '^test:' 40 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Eclipse Public License - v 1.0 2 | 3 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and 10 | 11 | b) in the case of each subsequent Contributor: 12 | 13 | i) changes to the Program, and 14 | 15 | ii) additions to the Program; 16 | 17 | where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. 18 | 19 | "Contributor" means any person or entity that distributes the Program. 20 | 21 | "Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. 22 | 23 | "Program" means the Contributions distributed in accordance with this Agreement. 24 | 25 | "Recipient" means anyone who receives the Program under this Agreement, including all Contributors. 26 | 27 | 2. GRANT OF RIGHTS 28 | 29 | a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. 30 | 31 | b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. 32 | 33 | c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. 34 | 35 | d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. 36 | 37 | 3. REQUIREMENTS 38 | 39 | A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: 40 | 41 | a) it complies with the terms and conditions of this Agreement; and 42 | 43 | b) its license agreement: 44 | 45 | i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; 46 | 47 | ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; 48 | 49 | iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and 50 | 51 | iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. 52 | 53 | When the Program is made available in source code form: 54 | 55 | a) it must be made available under this Agreement; and 56 | 57 | b) a copy of this Agreement must be included with each copy of the Program. 58 | 59 | Contributors may not remove or alter any copyright notices contained within the Program. 60 | 61 | Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. 62 | 63 | 4. COMMERCIAL DISTRIBUTION 64 | 65 | Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. 66 | 67 | For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. 68 | 69 | 5. NO WARRANTY 70 | 71 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. 72 | 73 | 6. DISCLAIMER OF LIABILITY 74 | 75 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 76 | 77 | 7. GENERAL 78 | 79 | If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. 80 | 81 | If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. 82 | 83 | All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. 84 | 85 | Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. 86 | 87 | This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | GREEN := $(shell tput -Txterm setaf 2) 2 | YELLOW := $(shell tput -Txterm setaf 3) 3 | WHITE := $(shell tput -Txterm setaf 7) 4 | RESET := $(shell tput -Txterm sgr0) 5 | 6 | 7 | .PHONY: all 8 | 9 | GO_PROJECT = github.com/shirou/mqttcli 10 | BUILD_DEST = build 11 | COMMIT_HASH=`git rev-parse --short HEAD` 12 | GIT_COMMIT = $(shell git rev-parse HEAD) 13 | GIT_SHA = $(shell git rev-parse --short HEAD) 14 | GIT_DIRTY = $(shell test -n "`git status --porcelain`" && echo "dirty" || echo "clean") 15 | 16 | LDFLAGS += -w -s -extldflags -static 17 | 18 | ifndef VERSION 19 | VERSION = DEV 20 | endif 21 | 22 | GOFLAGS := -ldflags "$(LDFLAGS)" 23 | 24 | ## Download dependencies and the run unit test and build the binary 25 | all: install clean test build 26 | 27 | ## Clean the dist directory 28 | clean: 29 | @rm -rf $(BUILD_DEST) 30 | 31 | ## download dependencies to run this project 32 | install: 33 | @which gox > /dev/null || go get github.com/mitchellh/gox 34 | @which dep > /dev/null || go get github.com/golang/dep/cmd/dep 35 | dep ensure -vendor-only 36 | 37 | ## Run unit test 38 | test: 39 | go test . 40 | ## Run for local development 41 | start: 42 | DATA_DIRECTORY="$$PWD/data" \ 43 | go run *.go 44 | 45 | ## Build the linux binary 46 | build: 47 | @rm -rf $(BUILD_DEST) 48 | @mkdir -p $(BUILD_DEST) > /dev/null 49 | @CGO_ENABLED=0 \ 50 | gox \ 51 | -output "$(BUILD_DEST)/{{.Dir}}_{{.OS}}_{{.Arch}}" \ 52 | $(GOFLAGS) \ 53 | . 54 | 55 | ## Prints the version info about the project 56 | info: 57 | @echo "Version: ${VERSION}" 58 | @echo "Git Commit: ${GIT_COMMIT}" 59 | @echo "Git Tree State: ${GIT_DIRTY}" 60 | 61 | ## Print the dependency graph and open in MAC 62 | dependencygraph: 63 | dep status -dot | dot -T png | open -f -a /Applications/Preview.app 64 | 65 | ## Prints this help command 66 | help: 67 | @echo '' 68 | @echo 'Usage:' 69 | @echo ' ${YELLOW}make${RESET} ${GREEN}${RESET}' 70 | @echo '' 71 | @echo 'Targets:' 72 | @awk '/^[a-zA-Z\-\_0-9]+:/ { \ 73 | helpMessage = match(lastLine, /^## (.*)/); \ 74 | if (helpMessage) { \ 75 | helpCommand = substr($$1, 0, index($$1, ":")-1); \ 76 | helpMessage = substr(lastLine, RSTART + 3, RLENGTH); \ 77 | printf " ${YELLOW}%-$(TARGET_MAX_CHAR_NUM)s${RESET}: ${GREEN}%s${RESET}\n", helpCommand, helpMessage; \ 78 | } \ 79 | } \ 80 | { lastLine = $$0 }' $(MAKEFILE_LIST) -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | mqttcli -- MQTT Client for shell scripting 2 | ================================================= 3 | 4 | mqttcli is an MQTT 3.1.1 Client which has almost same options with 5 | mosquitto_pub/sub. However, it has additional functionality and a 6 | pubsub command which is suite for the shell script pipelining. 7 | 8 | Install 9 | ============== 10 | 11 | Download from `here`_. Please choose your artitecture. (and chmod ugo+x if needed) 12 | 13 | .. _here: https://github.com/shirou/mqttcli/releases/latest 14 | 15 | 16 | :: 17 | 18 | curl https://raw.githubusercontent.com/shirou/mqttcli/master/install.sh | sh 19 | 20 | 21 | Or if you have golang environment, type this to build on your host. 22 | 23 | :: 24 | 25 | go get github.com/shirou/mqttcli 26 | 27 | 28 | Usage 29 | ============== 30 | 31 | common 32 | ---------- 33 | 34 | You can set host, port, username and password on the Environment variables. 35 | 36 | :: 37 | 38 | export MQTT_HOST="localhost" 39 | export MQTT_PORT="1883" 40 | export MQTT_USERNAME="user" 41 | export MQTT_PASSWORD="blahblah" 42 | 43 | or using a config file. You can specify a config file by ``--conf`` option. or automatically load from ``~/.mqttcli.cfg``. 44 | 45 | :: 46 | 47 | % mqttcli sub --conf yoursettings.json -t "some/topic" 48 | 49 | example: 50 | 51 | :: 52 | 53 | { 54 | "host": "localhost", 55 | "port": 1883, 56 | "username": "user", 57 | "password": "blahblah" 58 | } 59 | 60 | If you use AWS IoT, you can use these JSON as mqttcli config file, such as 61 | 62 | :: 63 | 64 | { 65 | "host": "A3HVHEAALED.iot.ap-northeast-1.amazonaws.com", 66 | "port": 8883, 67 | "clientId": "something", 68 | "thingName": "something", 69 | "caCert": "path/to/root-CA.crt", 70 | "clientCert": "path/to/2a338xx2xxf-certificate.pem.crt", 71 | "privateKey": "path/to/aad380efffx-private.pem.key" 72 | } 73 | 74 | You may change cert files path to where you placed. 75 | 76 | Pub 77 | ------- 78 | 79 | :: 80 | 81 | mqttcli pub -t "some/where" -m "your message" 82 | 83 | or 84 | 85 | tail -f /var/log/nginx.log | mqttcli pub -t "some/where" -s 86 | 87 | `-s` is diffrent from mosquitto_pub, it sends one line to one message. 88 | 89 | Sub 90 | ------ 91 | 92 | :: 93 | 94 | mqttcli sub -t "some/#" 95 | 96 | 97 | PubSub 98 | --------- 99 | 100 | Note: This subcommand is just a concept work. Might be delete in the future. 101 | 102 | Publish from stdin AND Subscribe from some topics and print stdout. 103 | 104 | :: 105 | 106 | tail -f /vag/log/nginx.log | mqttcli pubsub --pub "some/a" --sub "some/#" > filterd.log 107 | 108 | This is useful when other client manuplate something and send back to 109 | the topic. 110 | 111 | 112 | Reference 113 | ============== 114 | 115 | paho.mqtt.golang.git 116 | http://godoc.org/git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git 117 | 118 | 119 | License 120 | =========== 121 | 122 | Eclipse Public License - v 1.0 (same as Paho's) 123 | 124 | -------------------------------------------------------------------------------- /config.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io/ioutil" 7 | "os" 8 | "runtime" 9 | "strconv" 10 | "strings" 11 | 12 | log "github.com/Sirupsen/logrus" 13 | simpleJson "github.com/bitly/go-simplejson" 14 | MQTT "github.com/eclipse/paho.mqtt.golang" 15 | ) 16 | 17 | const DefaultConfigFilePath = "~/.mqttcli.cfg" 18 | 19 | type Config struct { 20 | Host string `json:"host"` 21 | Port int `json:"port"` 22 | UserName string `json:"username"` 23 | Password string `json:"password"` 24 | 25 | CaCert string `json:"caCert"` 26 | ClientCert string `json:"clientCert"` 27 | PrivateKey string `json:"privateKey"` 28 | } 29 | 30 | func (c *Config) UnmarshalJSON(data []byte) error { 31 | js, err := simpleJson.NewJson(data) 32 | if err != nil { 33 | return err 34 | } 35 | if c.Host, err = js.Get("host").String(); err != nil { 36 | c.Host = "" 37 | } 38 | // Port can be string either int 39 | if c.Port, err = js.Get("port").Int(); err != nil { 40 | p, err := js.Get("port").String() 41 | c.Port, err = strconv.Atoi(p) 42 | if err != nil { 43 | c.Port = 0 44 | } 45 | } 46 | if c.UserName, err = js.Get("username").String(); err != nil { 47 | c.UserName = "" 48 | } 49 | if c.Password, err = js.Get("password").String(); err != nil { 50 | c.Password = "" 51 | } 52 | if c.CaCert, err = js.Get("caCert").String(); err != nil { 53 | c.CaCert = "" 54 | } 55 | if c.ClientCert, err = js.Get("clientCert").String(); err != nil { 56 | c.ClientCert = "" 57 | } 58 | if c.PrivateKey, err = js.Get("privateKey").String(); err != nil { 59 | c.PrivateKey = "" 60 | } 61 | return nil 62 | } 63 | 64 | func readFromConfigFile(path string) (Config, error) { 65 | ret := Config{} 66 | 67 | b, err := ioutil.ReadFile(path) 68 | if err != nil { 69 | return ret, err 70 | } 71 | 72 | err = json.Unmarshal(b, &ret) 73 | if err != nil { 74 | return ret, err 75 | } 76 | 77 | return ret, nil 78 | } 79 | func UserHomeDir() string { 80 | if runtime.GOOS == "windows" { 81 | home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH") 82 | if home == "" { 83 | home = os.Getenv("USERPROFILE") 84 | } 85 | return home 86 | } 87 | return os.Getenv("HOME") 88 | } 89 | 90 | func existsDefaultConfigFile() (string, bool) { 91 | p := strings.Replace(DefaultConfigFilePath, "~", UserHomeDir(), 1) 92 | if _, err := os.Stat(p); err == nil { 93 | return p, true 94 | } else { 95 | return p, false 96 | } 97 | } 98 | 99 | func getSettingsFromFile(confPath string, opts *MQTT.ClientOptions) error { 100 | ret, err := readFromConfigFile(confPath) 101 | if err != nil { 102 | log.Error(err) 103 | return err 104 | } 105 | 106 | tlsConfig, ok, err := makeTlsConfig(ret.CaCert, ret.ClientCert, ret.PrivateKey, false) 107 | if err != nil { 108 | return err 109 | } 110 | if ok { 111 | opts.SetTLSConfig(tlsConfig) 112 | } 113 | 114 | if ret.Host != "" { 115 | if ret.Port == 0 { 116 | ret.Port = 1883 117 | } 118 | scheme := "tcp" 119 | if ret.Port == 8883 { 120 | scheme = "ssl" 121 | } 122 | brokerUri := fmt.Sprintf("%s://%s:%d", scheme, ret.Host, ret.Port) 123 | log.Infof("Broker URI(from config): %s", brokerUri) 124 | opts.AddBroker(brokerUri) 125 | } 126 | 127 | if ret.UserName != "" { 128 | opts.SetUsername(ret.UserName) 129 | } 130 | if ret.Password != "" { 131 | opts.SetPassword(ret.Password) 132 | } 133 | return nil 134 | } 135 | -------------------------------------------------------------------------------- /config_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "testing" 6 | ) 7 | 8 | func Test_ConfigUnmarshalJSON(t *testing.T) { 9 | c := Config{} 10 | 11 | j := `{"host": "h", "port": 1883}` 12 | err := json.Unmarshal([]byte(j), &c) 13 | if err != nil { 14 | t.Error(err) 15 | } 16 | if c.Port != 1883 { 17 | t.Error("port(int) is not correctly read") 18 | } 19 | if c.Host != "h" || c.UserName != "" || c.Password != "" { 20 | t.Error("parse failed") 21 | } 22 | 23 | j = `{"host": "h", "port": "1883", "username": "u"}` 24 | err = json.Unmarshal([]byte(j), &c) 25 | if err != nil { 26 | t.Error(err) 27 | } 28 | if c.Port != 1883 { 29 | t.Error("port(string) is not correctly read") 30 | } 31 | if c.Host != "h" || c.UserName != "u" || c.Password != "" { 32 | t.Error("parse failed with username set") 33 | } 34 | } 35 | 36 | func Test_ConfigCert(t *testing.T) { 37 | c := Config{} 38 | 39 | j := `{"caCert": "ca", "clientCert": "client", "privateKey": "key"}` 40 | err := json.Unmarshal([]byte(j), &c) 41 | if err != nil { 42 | t.Error(err) 43 | } 44 | if c.CaCert != "ca" || c.ClientCert != "client" || c.PrivateKey != "key" { 45 | t.Errorf("parse failed, %+v", c) 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/shirou/mqttcli 2 | 3 | go 1.15 4 | 5 | require ( 6 | github.com/Sirupsen/logrus v1.0.5 7 | github.com/bitly/go-simplejson v0.5.1 8 | github.com/eclipse/paho.mqtt.golang v1.4.3 9 | github.com/mattn/go-colorable v0.1.13 10 | github.com/onsi/ginkgo v1.14.2 // indirect 11 | github.com/onsi/gomega v1.10.4 // indirect 12 | github.com/sirupsen/logrus v1.7.0 // indirect 13 | github.com/stretchr/testify v1.6.1 // indirect 14 | github.com/urfave/cli/v2 v2.25.7 15 | gopkg.in/airbrake/gobrake.v2 v2.0.9 // indirect 16 | gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2 // indirect 17 | gopkg.in/yaml.v2 v2.4.0 // indirect 18 | ) 19 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= 2 | github.com/Sirupsen/logrus v1.0.5 h1:447dy9LxSj+Iaa2uN3yoFHOzU9yJcJYiQPtNz8OXtv0= 3 | github.com/Sirupsen/logrus v1.0.5/go.mod h1:rmk17hk6i8ZSAJkSDa7nOxamrG+SP4P0mm+DAvExv4U= 4 | github.com/bitly/go-simplejson v0.5.1 h1:xgwPbetQScXt1gh9BmoJ6j9JMr3TElvuIyjR8pgdoow= 5 | github.com/bitly/go-simplejson v0.5.1/go.mod h1:YOPVLzCfwK14b4Sff3oP1AmGhI9T9Vsg84etUnlyp+Q= 6 | github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= 7 | github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= 8 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 9 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 10 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 11 | github.com/eclipse/paho.mqtt.golang v1.4.3 h1:2kwcUGn8seMUfWndX0hGbvH8r7crgcJguQNCyp70xik= 12 | github.com/eclipse/paho.mqtt.golang v1.4.3/go.mod h1:CSYvoAlsMkhYOXh/oKyxa8EcBci6dVkLCbo5tTC1RIE= 13 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= 14 | github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= 15 | github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= 16 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 17 | github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= 18 | github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= 19 | github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= 20 | github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= 21 | github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= 22 | github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= 23 | github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= 24 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 25 | github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 26 | github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= 27 | github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 28 | github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= 29 | github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= 30 | github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= 31 | github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= 32 | github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= 33 | github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ= 34 | github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= 35 | github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= 36 | github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= 37 | github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 38 | github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= 39 | github.com/onsi/ginkgo v1.14.2 h1:8mVmC9kjFFmA8H4pKMUhcblgifdkOIXPvbhN1T36q1M= 40 | github.com/onsi/ginkgo v1.14.2/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= 41 | github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= 42 | github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= 43 | github.com/onsi/gomega v1.10.4 h1:NiTx7EEvBzu9sFOD1zORteLSt3o8gnlvZZwSE9TnY9U= 44 | github.com/onsi/gomega v1.10.4/go.mod h1:g/HbgYopi++010VEqkFgJHKC09uJiW9UkXvMUuKHUCQ= 45 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 46 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 47 | github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= 48 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 49 | github.com/sirupsen/logrus v1.7.0 h1:ShrD1U9pZB12TX0cVy0DtePoCH97K8EtX+mg7ZARUtM= 50 | github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= 51 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 52 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 53 | github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= 54 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 55 | github.com/urfave/cli/v2 v2.25.7 h1:VAzn5oq403l5pHjc4OhD54+XGO9cdKVL/7lDjF+iKUs= 56 | github.com/urfave/cli/v2 v2.25.7/go.mod h1:8qnjx1vcq5s2/wpsqoZFndg2CE5tNFyrTvS6SinrnYQ= 57 | github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= 58 | github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= 59 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= 60 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 61 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= 62 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg= 63 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= 64 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= 65 | golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= 66 | golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 67 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 68 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 69 | golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= 70 | golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= 71 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 72 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= 73 | golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= 74 | golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= 75 | golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= 76 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 77 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 78 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 79 | golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= 80 | golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 81 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 82 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 83 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 84 | golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 85 | golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 86 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 87 | golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 88 | golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 89 | golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 90 | golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 91 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 92 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 93 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 94 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 95 | golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 96 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 97 | golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= 98 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 99 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 100 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 101 | golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= 102 | golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= 103 | golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= 104 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 105 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= 106 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 107 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 108 | golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 109 | golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= 110 | golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= 111 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 112 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 113 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= 114 | golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= 115 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 116 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= 117 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 118 | google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= 119 | google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= 120 | google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= 121 | google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= 122 | google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= 123 | google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= 124 | google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= 125 | gopkg.in/airbrake/gobrake.v2 v2.0.9 h1:7z2uVWwn7oVeeugY1DtlPAy5H+KYgB1KeKTnqjNatLo= 126 | gopkg.in/airbrake/gobrake.v2 v2.0.9/go.mod h1:/h5ZAUhDkGaJfjzjKLSjv6zCL6O0LLBxU4K+aSYdM/U= 127 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 128 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 129 | gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= 130 | gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2 h1:OAj3g0cR6Dx/R07QgQe8wkA9RNjB2u4i700xBkIT4e0= 131 | gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2/go.mod h1:Xk6kEKp8OKb+X14hQBKWaSkCsqBpgog8nAV2xsGOxlo= 132 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= 133 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= 134 | gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 135 | gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 136 | gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= 137 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 138 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 139 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 140 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 141 | -------------------------------------------------------------------------------- /install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | 3 | # Based on https://raw.githubusercontent.com/golang/dep/master/install.sh 4 | 5 | RELEASES_URL="https://github.com/shirou/mqttcli/releases" 6 | INSTALL_NAME="mqttcli" 7 | if [ -z ${INSTALL_DIRECTORY} ] 8 | then 9 | INSTALL_DIRECTORY="${HOME}/bin" 10 | fi 11 | 12 | downloadJSON() { 13 | url="$2" 14 | 15 | echo "Fetching $url.." 16 | if test -x "$(command -v curl)"; then 17 | response=$(curl -s -L -w 'HTTPSTATUS:%{http_code}' -H 'Accept: application/json' "$url") 18 | body=$(echo "$response" | sed -e 's/HTTPSTATUS\:.*//g') 19 | code=$(echo "$response" | tr -d '\n' | sed -e 's/.*HTTPSTATUS://') 20 | elif test -x "$(command -v wget)"; then 21 | temp=$(mktemp) 22 | body=$(wget -q --header='Accept: application/json' -O - --server-response "$url" 2> "$temp") 23 | code=$(awk '/^ HTTP/{print $2}' < "$temp" | tail -1) 24 | rm "$temp" 25 | else 26 | echo "Neither curl nor wget was available to perform http requests." 27 | exit 1 28 | fi 29 | if [ "$code" != 200 ]; then 30 | echo "Request failed with code $code" 31 | exit 1 32 | fi 33 | 34 | eval "$1='$body'" 35 | } 36 | 37 | downloadFile() { 38 | url="$1" 39 | destination="$2" 40 | 41 | echo "Fetching $url.." 42 | if test -x "$(command -v curl)"; then 43 | code=$(curl -s -w '%{http_code}' -L "$url" -o "$destination") 44 | elif test -x "$(command -v wget)"; then 45 | code=$(wget -q -O "$destination" --server-response "$url" 2>&1 | awk '/^ HTTP/{print $2}' | tail -1) 46 | else 47 | echo "Neither curl nor wget was available to perform http requests." 48 | exit 1 49 | fi 50 | 51 | if [ "$code" != 200 ]; then 52 | echo "Request failed with code $code" 53 | exit 1 54 | fi 55 | } 56 | 57 | initArch() { 58 | ARCH=$(uname -m) 59 | if [ -n "$DEP_ARCH" ]; then 60 | echo "Using DEP_ARCH" 61 | ARCH="$DEP_ARCH" 62 | fi 63 | case $ARCH in 64 | amd64) ARCH="amd64";; 65 | x86_64) ARCH="amd64";; 66 | i386) ARCH="386";; 67 | *) echo "Architecture ${ARCH} is not supported by this installation script"; exit 1;; 68 | esac 69 | echo "ARCH = $ARCH" 70 | } 71 | 72 | initOS() { 73 | OS=$(uname | tr '[:upper:]' '[:lower:]') 74 | if [ -n "$DEP_OS" ]; then 75 | echo "Using DEP_OS" 76 | OS="$DEP_OS" 77 | fi 78 | case "$OS" in 79 | darwin) OS='darwin';; 80 | linux) OS='linux';; 81 | freebsd) OS='freebsd';; 82 | mingw*) OS='windows';; 83 | msys*) OS='windows';; 84 | *) echo "OS ${OS} is not supported by this installation script"; exit 1;; 85 | esac 86 | echo "OS = $OS" 87 | } 88 | 89 | # identify platform based on uname output 90 | initArch 91 | initOS 92 | 93 | if [ ! -d $INSTALL_DIRECTORY ] 94 | then 95 | mkdir -p $INSTALL_DIRECTORY 96 | fi 97 | 98 | # determine install directory if required 99 | echo "Will install into $INSTALL_DIRECTORY" 100 | 101 | # assemble expected release artifact name 102 | BINARY="mqttcli_${OS}_${ARCH}" 103 | 104 | # add .exe if on windows 105 | if [ "$OS" = "windows" ]; then 106 | BINARY="$BINARY.exe" 107 | fi 108 | 109 | # if DEP_RELEASE_TAG was not provided, assume latest 110 | if [ -z "$DEP_RELEASE_TAG" ]; then 111 | downloadJSON LATEST_RELEASE "$RELEASES_URL/latest" 112 | DEP_RELEASE_TAG=$(echo "${LATEST_RELEASE}" | tr -s '\n' ' ' | sed 's/.*"tag_name":"//' | sed 's/".*//' ) 113 | fi 114 | echo "Release Tag = $DEP_RELEASE_TAG" 115 | 116 | # fetch the real release data to make sure it exists before we attempt a download 117 | downloadJSON RELEASE_DATA "$RELEASES_URL/tag/$DEP_RELEASE_TAG" 118 | 119 | BINARY_URL="$RELEASES_URL/download/$DEP_RELEASE_TAG/$BINARY" 120 | DOWNLOAD_FILE=$(mktemp) 121 | 122 | downloadFile "$BINARY_URL" "$DOWNLOAD_FILE" 123 | 124 | echo "Setting executable permissions." 125 | chmod +x "$DOWNLOAD_FILE" 126 | 127 | if [ "$OS" = "windows" ]; then 128 | INSTALL_NAME="$INSTALL_NAME.exe" 129 | fi 130 | 131 | echo "Moving executable to $INSTALL_DIRECTORY/$INSTALL_NAME" 132 | mv "$DOWNLOAD_FILE" "$INSTALL_DIRECTORY/$INSTALL_NAME" 133 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | stdlog "log" 6 | "os" 7 | "sync" 8 | "time" 9 | 10 | log "github.com/Sirupsen/logrus" 11 | MQTT "github.com/eclipse/paho.mqtt.golang" 12 | colorable "github.com/mattn/go-colorable" 13 | "github.com/urfave/cli/v2" 14 | ) 15 | 16 | var usage = ` 17 | Usage here 18 | ` 19 | 20 | var version string 21 | 22 | func init() { 23 | log.SetLevel(log.WarnLevel) 24 | log.SetOutput(colorable.NewColorableStdout()) 25 | } 26 | 27 | // connects MQTT broker 28 | func connect(c *cli.Context, opts *MQTT.ClientOptions, subscribed map[string]byte) (*MQTTClient, error) { 29 | willPayload := c.String("will-payload") 30 | willQoS := c.Int("will-qos") 31 | willRetain := c.Bool("will-retain") 32 | willTopic := c.String("will-topic") 33 | if willPayload != "" && willTopic != "" { 34 | opts.SetWill(willTopic, willPayload, byte(willQoS), willRetain) 35 | } 36 | 37 | client := &MQTTClient{Opts: opts} 38 | client.lock = new(sync.Mutex) 39 | client.Subscribed = subscribed 40 | 41 | opts.SetOnConnectHandler(client.SubscribeOnConnect) 42 | opts.SetConnectionLostHandler(client.ConnectionLost) 43 | 44 | _, err := client.Connect() 45 | if err != nil { 46 | return nil, err 47 | } 48 | 49 | return client, nil 50 | } 51 | 52 | func pubsub(c *cli.Context) error { 53 | setDebugLevel(c) 54 | opts, err := NewOption(c) 55 | if err != nil { 56 | log.Error(err) 57 | os.Exit(1) 58 | } 59 | 60 | qos := c.Int("q") 61 | subtopic := c.String("sub") 62 | if subtopic == "" { 63 | log.Errorf("Please specify sub topic") 64 | os.Exit(1) 65 | } 66 | log.Infof("Sub Topic: %s", subtopic) 67 | pubtopic := c.String("pub") 68 | if pubtopic == "" { 69 | log.Errorf("Please specify pub topic") 70 | os.Exit(1) 71 | } 72 | log.Infof("Pub Topic: %s", pubtopic) 73 | retain := c.Bool("r") 74 | 75 | subscribed := map[string]byte{ 76 | subtopic: byte(0), 77 | } 78 | 79 | client, err := connect(c, opts, subscribed) 80 | if err != nil { 81 | log.Error(err) 82 | os.Exit(1) 83 | } 84 | 85 | go func() { 86 | // Read from Stdin and publish 87 | scanner := bufio.NewScanner(os.Stdin) 88 | for scanner.Scan() { 89 | err = client.Publish(pubtopic, []byte(scanner.Text()), qos, retain, false) 90 | if err != nil { 91 | log.Error(err) 92 | } 93 | } 94 | }() 95 | 96 | // while loop 97 | for { 98 | time.Sleep(1 * time.Second) 99 | } 100 | return nil 101 | } 102 | 103 | func main() { 104 | app := cli.NewApp() 105 | app.Name = "mqttcli" 106 | app.Usage = usage 107 | app.Version = version 108 | 109 | cli.HelpFlag = &cli.BoolFlag{ 110 | Name: "help", 111 | Usage: usage, 112 | } 113 | 114 | commonFlags := []cli.Flag{ 115 | &cli.StringFlag{ 116 | Name: "host", 117 | Aliases: []string{"h"}, 118 | Value: "", 119 | Usage: "mqtt host to connect to. Defaults is localhost", 120 | EnvVars: []string{"MQTT_HOST"}}, 121 | &cli.IntFlag{ 122 | Name: "port", 123 | Aliases: []string{"p"}, 124 | Value: 1883, 125 | Usage: "network port to connect to. Defaults is 1883", 126 | EnvVars: []string{"MQTT_PORT"}}, 127 | &cli.StringFlag{ 128 | Name: "user", 129 | Aliases: []string{"u"}, 130 | Value: "", 131 | Usage: "provide a username", 132 | EnvVars: []string{"MQTT_USERNAME"}}, 133 | &cli.StringFlag{ 134 | Name: "password", 135 | Aliases: []string{"P"}, 136 | Value: "", 137 | Usage: "provide a password", 138 | EnvVars: []string{"MQTT_PASSWORD"}}, 139 | &cli.StringFlag{ 140 | Name: "t", 141 | Value: "", 142 | Usage: "mqtt topic to publish to.", 143 | }, 144 | &cli.IntFlag{ 145 | Name: "q", 146 | Value: 0, 147 | Usage: "QoS", 148 | }, 149 | &cli.StringFlag{ 150 | Name: "cafile", 151 | Value: "", 152 | Usage: "CA certificates", 153 | }, 154 | &cli.StringFlag{ 155 | Name: "cert", 156 | Value: "", 157 | Usage: "Client certificates", 158 | }, 159 | &cli.StringFlag{ 160 | Name: "key", 161 | Value: "", 162 | Usage: "Client private key", 163 | }, 164 | &cli.StringFlag{ 165 | Name: "i", 166 | Value: "", 167 | Usage: "ClientiId. Defaults random.", 168 | }, 169 | &cli.StringFlag{ 170 | Name: "m", 171 | Value: "test message", 172 | Usage: "Message body", 173 | }, 174 | &cli.BoolFlag{ 175 | Name: "r", 176 | Usage: "message should be retained.", 177 | }, 178 | &cli.BoolFlag{ 179 | Name: "d", 180 | Usage: "enable debug messages", 181 | }, 182 | &cli.BoolFlag{ 183 | Name: "dd", 184 | Usage: "enable debug messages", 185 | }, 186 | &cli.BoolFlag{ 187 | Name: "ddd", 188 | Usage: "enable debug messages", 189 | }, 190 | &cli.BoolFlag{ 191 | Name: "dddd", 192 | Usage: "enable debug messages", 193 | }, 194 | &cli.BoolFlag{ 195 | Name: "ddddd", 196 | Usage: "enable debug messages", 197 | }, 198 | &cli.BoolFlag{ 199 | Name: "insecure", 200 | Usage: "do not check that the server certificate", 201 | }, 202 | &cli.StringFlag{ 203 | Name: "conf", 204 | Value: DefaultConfigFilePath, 205 | Usage: "config file path", 206 | EnvVars: []string{"MQTTCLI_CONFPATH"}}, 207 | &cli.StringFlag{ 208 | Name: "will-payload", 209 | Value: "", 210 | Usage: "payload for the client Will", 211 | }, 212 | &cli.IntFlag{ 213 | Name: "will-qos", 214 | Value: 0, 215 | Usage: "QoS level for the client Will", 216 | }, 217 | &cli.BoolFlag{ 218 | Name: "will-retain", 219 | Usage: "if given, make the client Will retained", 220 | }, 221 | &cli.StringFlag{ 222 | Name: "will-topic", 223 | Value: "", 224 | Usage: "the topic on which to publish the client Will", 225 | }, 226 | } 227 | pubFlags := append(commonFlags, 228 | &cli.BoolFlag{ 229 | Name: "s", 230 | Usage: "read message from stdin, sending line by line as a message", 231 | }, 232 | ) 233 | subFlags := append(commonFlags, 234 | &cli.BoolFlag{ 235 | Name: "c", 236 | Usage: "disable 'clean session'", 237 | }, 238 | ) 239 | pubsubFlags := append(commonFlags, 240 | &cli.StringFlag{ 241 | Name: "pub", 242 | Usage: "publish topic", 243 | }, 244 | &cli.StringFlag{ 245 | Name: "sub", 246 | Usage: "subscribe topic", 247 | }, 248 | ) 249 | 250 | app.Commands = []*cli.Command{ 251 | { 252 | Name: "pub", 253 | Usage: "publish", 254 | Flags: pubFlags, 255 | Action: publish, 256 | }, 257 | { 258 | Name: "sub", 259 | Usage: "subscribe", 260 | Flags: subFlags, 261 | Action: subscribe, 262 | }, 263 | { 264 | Name: "pubsub", 265 | Usage: "subscribe and publish", 266 | Flags: pubsubFlags, 267 | Action: pubsub, 268 | }, 269 | } 270 | err := app.Run(os.Args) 271 | if err != nil { 272 | log.Error(err) 273 | } 274 | } 275 | 276 | func setDebugLevel(c *cli.Context) { 277 | if c.Bool("d") { 278 | log.SetLevel(log.DebugLevel) 279 | } else if c.Bool("dd") { 280 | log.SetLevel(log.DebugLevel) 281 | MQTT.WARN = stdlog.New(os.Stdout, "", stdlog.LstdFlags) 282 | } else if c.Bool("ddd") { 283 | log.SetLevel(log.DebugLevel) 284 | MQTT.DEBUG = stdlog.New(os.Stdout, "", stdlog.LstdFlags) 285 | } 286 | } 287 | -------------------------------------------------------------------------------- /mqtt.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/rand" 5 | "crypto/tls" 6 | "crypto/x509" 7 | "fmt" 8 | "io/ioutil" 9 | "sync" 10 | 11 | log "github.com/Sirupsen/logrus" 12 | MQTT "github.com/eclipse/paho.mqtt.golang" 13 | "github.com/urfave/cli/v2" 14 | ) 15 | 16 | var MaxClientIdLen = 8 17 | var MaxRetryCount = 3 18 | 19 | type MQTTClient struct { 20 | Client MQTT.Client 21 | Opts *MQTT.ClientOptions 22 | RetryCount int 23 | Subscribed map[string]byte 24 | 25 | lock *sync.Mutex // use for reconnect 26 | } 27 | 28 | // Connects connect to the MQTT broker with Options. 29 | func (m *MQTTClient) Connect() (MQTT.Client, error) { 30 | 31 | m.Client = MQTT.NewClient(m.Opts) 32 | 33 | log.Infof("connecting...") 34 | 35 | if token := m.Client.Connect(); token.Wait() && token.Error() != nil { 36 | return nil, token.Error() 37 | } 38 | return m.Client, nil 39 | } 40 | 41 | func (m *MQTTClient) Publish(topic string, payload []byte, qos int, retain bool, sync bool) error { 42 | token := m.Client.Publish(topic, byte(qos), retain, payload) 43 | 44 | if sync == true { 45 | token.Wait() 46 | } 47 | 48 | return token.Error() 49 | } 50 | 51 | func (m *MQTTClient) Disconnect() error { 52 | if m.Client.IsConnected() { 53 | m.Client.Disconnect(20) 54 | log.Info("client disconnected") 55 | } 56 | return nil 57 | } 58 | 59 | func (m *MQTTClient) SubscribeOnConnect(client MQTT.Client) { 60 | log.Infof("client connected") 61 | 62 | if len(m.Subscribed) > 0 { 63 | token := client.SubscribeMultiple(m.Subscribed, m.onMessageReceived) 64 | token.Wait() 65 | if token.Error() != nil { 66 | log.Error(token.Error()) 67 | } 68 | } 69 | } 70 | 71 | func (m *MQTTClient) ConnectionLost(client MQTT.Client, reason error) { 72 | log.Errorf("client disconnected: %s", reason) 73 | } 74 | 75 | func (m *MQTTClient) onMessageReceived(client MQTT.Client, message MQTT.Message) { 76 | log.Infof("topic:%s / msg:%s", message.Topic(), message.Payload()) 77 | fmt.Println(string(message.Payload())) 78 | } 79 | 80 | func getCertPool(pemPath string) (*x509.CertPool, error) { 81 | certs := x509.NewCertPool() 82 | 83 | pemData, err := ioutil.ReadFile(pemPath) 84 | if err != nil { 85 | return nil, err 86 | } 87 | certs.AppendCertsFromPEM(pemData) 88 | return certs, nil 89 | } 90 | 91 | // getRandomClientId returns randomized ClientId. 92 | func getRandomClientId() string { 93 | const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 94 | var bytes = make([]byte, MaxClientIdLen) 95 | rand.Read(bytes) 96 | for i, b := range bytes { 97 | bytes[i] = alphanum[b%byte(len(alphanum))] 98 | } 99 | return "mqttcli-" + string(bytes) 100 | } 101 | 102 | // NewOption returns ClientOptions via parsing command line options. 103 | func NewOption(c *cli.Context) (*MQTT.ClientOptions, error) { 104 | opts := MQTT.NewClientOptions() 105 | 106 | conf := c.String("conf") 107 | 108 | defaultConf, exists := existsDefaultConfigFile() 109 | 110 | if conf != DefaultConfigFilePath { 111 | log.Debugf("reading from config file: %s", conf) 112 | if err := getSettingsFromFile(conf, opts); err != nil { 113 | return nil, err 114 | } 115 | } else if conf != "" && exists { 116 | log.Debugf("reading from default config file: %s", defaultConf) 117 | if err := getSettingsFromFile(defaultConf, opts); err != nil { 118 | return nil, err 119 | } 120 | } 121 | 122 | // override 123 | host := c.String("host") 124 | port := c.Int("p") 125 | 126 | clientId := c.String("i") 127 | if clientId == "" { 128 | clientId = getRandomClientId() 129 | } 130 | opts.SetClientID(clientId) 131 | 132 | scheme := "tcp" 133 | if port == 8883 { 134 | scheme = "ssl" 135 | } 136 | 137 | cafile := c.String("cafile") 138 | key := c.String("key") 139 | cert := c.String("cert") 140 | insecure := c.Bool("insecure") 141 | if cafile != "" || key != "" || cert != "" { 142 | log.Debugf("reading from args") 143 | tlsConfig, ok, err := makeTlsConfig(cafile, cert, key, insecure) 144 | if err != nil { 145 | return nil, err 146 | } 147 | if ok { 148 | opts.SetTLSConfig(tlsConfig) 149 | scheme = "ssl" 150 | } 151 | } 152 | 153 | user := c.String("u") 154 | if user != "" { 155 | opts.SetUsername(user) 156 | } 157 | password := c.String("P") 158 | if password != "" { 159 | opts.SetPassword(password) 160 | } 161 | 162 | if host == "" { 163 | host = "localhost" 164 | } 165 | if len(opts.Servers) == 0 { 166 | brokerUri := fmt.Sprintf("%s://%s:%d", scheme, host, port) 167 | log.Infof("Broker URI: %s", brokerUri) 168 | 169 | opts.AddBroker(brokerUri) 170 | } 171 | 172 | opts.SetAutoReconnect(true) 173 | return opts, nil 174 | } 175 | 176 | // makeTlsConfig creats new tls.Config. If returned ok is false, does not need set to MQTToption. 177 | func makeTlsConfig(cafile, cert, key string, insecure bool) (*tls.Config, bool, error) { 178 | TLSConfig := &tls.Config{InsecureSkipVerify: false} 179 | var ok bool 180 | if insecure { 181 | TLSConfig.InsecureSkipVerify = true 182 | ok = true 183 | } 184 | if cafile != "" { 185 | certPool, err := getCertPool(cafile) 186 | if err != nil { 187 | return nil, false, err 188 | } 189 | TLSConfig.RootCAs = certPool 190 | ok = true 191 | } 192 | if cert != "" { 193 | certPool, err := getCertPool(cert) 194 | if err != nil { 195 | return nil, false, err 196 | } 197 | TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert 198 | TLSConfig.ClientCAs = certPool 199 | ok = true 200 | } 201 | if key != "" { 202 | if cert == "" { 203 | return nil, false, fmt.Errorf("key specified but cert is not specified") 204 | } 205 | cert, err := tls.LoadX509KeyPair(cert, key) 206 | if err != nil { 207 | return nil, false, err 208 | } 209 | TLSConfig.Certificates = []tls.Certificate{cert} 210 | ok = true 211 | } 212 | return TLSConfig, ok, nil 213 | } 214 | -------------------------------------------------------------------------------- /publish.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "os" 6 | 7 | log "github.com/Sirupsen/logrus" 8 | "github.com/urfave/cli/v2" 9 | ) 10 | 11 | func publish(c *cli.Context) error { 12 | setDebugLevel(c) 13 | 14 | opts, err := NewOption(c) 15 | if err != nil { 16 | log.Error(err) 17 | os.Exit(1) 18 | } 19 | client, err := connect(c, opts, map[string]byte{}) 20 | if err != nil { 21 | log.Error(err) 22 | os.Exit(1) 23 | } 24 | 25 | qos := c.Int("q") 26 | topic := c.String("t") 27 | if topic == "" { 28 | log.Errorf("Please specify topic") 29 | os.Exit(1) 30 | } 31 | log.Infof("Topic: %s", topic) 32 | 33 | retain := c.Bool("r") 34 | 35 | if c.Bool("s") { 36 | // Read from Stdin 37 | scanner := bufio.NewScanner(os.Stdin) 38 | for scanner.Scan() { 39 | err = client.Publish(topic, scanner.Bytes(), qos, retain, true) 40 | if err != nil { 41 | log.Error(err) 42 | } 43 | 44 | } 45 | } else { 46 | payload := c.String("m") 47 | err = client.Publish(topic, []byte(payload), qos, retain, true) 48 | if err != nil { 49 | log.Error(err) 50 | } 51 | 52 | } 53 | log.Info("Published") 54 | return client.Disconnect() 55 | } 56 | -------------------------------------------------------------------------------- /subscribe.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | "time" 6 | 7 | log "github.com/Sirupsen/logrus" 8 | "github.com/urfave/cli/v2" 9 | ) 10 | 11 | func subscribe(c *cli.Context) error { 12 | setDebugLevel(c) 13 | opts, err := NewOption(c) 14 | if err != nil { 15 | log.Error(err) 16 | os.Exit(1) 17 | } 18 | opts.SetKeepAlive(time.Second * 60) 19 | 20 | if c.Bool("c") { 21 | clientId := c.String("i") 22 | if clientId == "" { 23 | log.Warn("clean Flag does not work without client id") 24 | } 25 | 26 | opts.SetCleanSession(false) 27 | } 28 | 29 | qos := c.Int("q") 30 | topic := c.String("t") 31 | if topic == "" { 32 | log.Errorf("Please specify topic") 33 | os.Exit(1) 34 | } 35 | log.Infof("Topic: %s", topic) 36 | 37 | subscribed := map[string]byte{ 38 | topic: byte(qos), 39 | } 40 | 41 | _, err = connect(c, opts, subscribed) 42 | if err != nil { 43 | log.Error(err) 44 | os.Exit(1) 45 | } 46 | 47 | // loops forever 48 | for { 49 | time.Sleep(time.Second) 50 | } 51 | 52 | return nil 53 | } 54 | --------------------------------------------------------------------------------