【Golang】jsonをstructに変換したい
どうもてぃ。
絶賛golangをキャッチアップ中です。
APIとしてgolangを使用し、フロントエンドはnextjs/typescriptで自分で実装していく可能性があるのでどんどんアウトプットしていきます。
環境
やりたいこと
題の通り。
色んなサービスのAPIを触る際、受取側(golang)でstructを作ってやりたいが毎回作るのはめんどうくさい(ものによってはレスポンスめっちゃ多いのあるし)。
例えば、有名な決済サービスサイトstripeを例にしてみる。
{ "id": "txn_1032HU2eZvKYlo2CEPtcnUvl", "object": "balance_transaction", "amount": 400, "available_on": 1386374400, "created": 1385814763, "currency": "usd", "description": "Charge for test@example.com", "exchange_rate": null, "fee": 42, "fee_details": [ { "amount": 42, "application": null, "currency": "usd", "description": "Stripe processing fees", "type": "stripe_fee" } ], "net": 358, "reporting_category": "charge", "source": "ch_1032HU2eZvKYlo2C0FuZb3X7", "status": "available", "type": "charge" }
The balance transaction object
のレスポンスはこんな感じで、まあまあ長いし同じように他のレスポンスのstructを作るとなると結構面倒くさい。
JSON-to-Goを使う
すばらしいサービスです。
jsonをstructに変換してくれます。
上のjsonを入れると
ttype AutoGenerated struct { ID string `json:"id"` Object string `json:"object"` Amount int `json:"amount"` AvailableOn int `json:"available_on"` Created int `json:"created"` Currency string `json:"currency"` Description string `json:"description"` ExchangeRate interface{} `json:"exchange_rate"` Fee int `json:"fee"` FeeDetails []struct { Amount int `json:"amount"` Application interface{} `json:"application"` Currency string `json:"currency"` Description string `json:"description"` Type string `json:"type"` } `json:"fee_details"` Net int `json:"net"` ReportingCategory string `json:"reporting_category"` Source string `json:"source"` Status string `json:"status"` Type string `json:"type"` }
こんな感じでstructに変換してくれます。
structの名前はデフォルトでAutoGenerated
になるので適宜変えるといい感じに出来ますね。
整理すると
type BalanceTransactionObject struct { ID string `json:"id"` Object string `json:"object"` Amount int `json:"amount"` AvailableOn int `json:"available_on"` Created int `json:"created"` Currency string `json:"currency"` Description string `json:"description"` ExchangeRate interface{} `json:"exchange_rate"` Fee int `json:"fee"` FeeDetails []FeeDetails`json:"fee_details"` Net int `json:"net"` ReportingCategory string `json:"reporting_category"` Source string `json:"source"` Status string `json:"status"` Type string `json:"type"` } type FeeDetails struct { Amount int `json:"amount"` Application interface{} `json:"application"` Currency string `json:"currency"` Description string `json:"description"` Type string `json:"type"` }
素晴らしすぎる。
おわり
記事書いたあとに気づいたんですが、JSON-to-GoのInline type Definitions
のチェックボックを外すと整理したstructと同じものを作成できますね。。。
まあ、そういう日もあるか。
備忘録的な感じなので、結構有名なサービスで他にも良いのあったらぜひぜひコメントお願いします。
【CentOS】File contains parsing errorでyumコマンドが使えない
どうもてぃ。
久々に起動したGCE vmインスタンスでエラーが出たので改修
起こった現象
$ yum upgrade 読み込んだプラグイン:fastestmirror File contains parsing errors: file:///etc/yum.repos.d/pgdg-redhat-all.repo [line 196]: [pgdg96-updates-debuginfo]k [line 203]: [pgdg95-updates-debuginfo]k
なんか196行目・203行目でエラー出てるっぽい。
ファイルの確認
/etc/yum.repos.d/pgdg-redhat-all.repo
を確認してみる。
$ sudo vim /etc/yum.repos.d/pgdg-redhat-all.repo ・ ・ ・ [pgdg10-updates-debuginfo] name=PostgreSQL 10 for RHEL/CentOS $releasever - $basearch - Debuginfo baseurl=https://download.postgresql.org/pub/repos/yum/debug/10/redhat/rhel-$releasever-$basearch enabled=0 gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG [pgdg96-updates-debuginfo]k name=PostgreSQL 9.6 for RHEL/CentOS $releasever - $basearch - Debuginfo baseurl=https://download.postgresql.org/pub/repos/yum/debug/9.6/redhat/rhel-$releasever-$basearch enabled=0 gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG [pgdg95-updates-debuginfo]k name=PostgreSQL 9.5 for RHEL/CentOS $releasever - $basearch - Debuginfo baseurl=https://download.postgresql.org/pub/repos/yum/debug/9.5/redhat/rhel-$releasever-$basearch enabled=0 gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG
パッケージ名?の末尾に謎のk
が入ってるものが…
一旦k
を削除して保存。
解決
sudo yum upgrade
で無事パッケージのupgradeが走りました。
そもそもどのタイミングであの場所にkが入ったのか…謎すぎる。
【Golang】realizeコマンドが使えない
どうもてぃです。
asdfを使ってインストールしたgolangのgo getしたパッケージが使えなかったので備忘録として。
環境
試したこと
とりあえずrealizeとやらが便利らしいのでgithubの手順をおっていれてみることに。
$ go get -u https://github.com/oxequa/realize $ realize start _ _ ___ ___ _ __ ___ _ __ ___ __ _ _ __ __| | _ __ ___ | |_ / __/ _ \| '_ ` _ \| '_ ` _ \ / _` | '_ \ / _` | | '_ \ / _ \| __| | (_| (_) | | | | | | | | | | | (_| | | | | (_| | | | | | (_) | |_ \___\___/|_| |_| |_|_| |_| |_|\__,_|_| |_|\__,_| |_| |_|\___/ \__| __ _ / _| ___ _ _ _ __ __| | | |_ / _ \| | | | '_ \ / _` | | _| (_) | |_| | | | | (_| | |_| \___/ \__,_|_| |_|\__,_|
とりあえず動かない。
調査
定石通り golang realize command not found
みたいな感じで検索。
まあ予想通りissueに出てきた。
$GOPATH
関連っぽい。
とりあえず自分の環境を確認してみる。
$ go env | grep PATH GOPATH="/home/motty/.asdf/installs/golang/1.14.4/packages" $ echo $GOPATH # => 無
どういう状況になってるのか全くわからん…。
asdfのGOPATHについて調べる
そもそもrealizeが入ってるのかどうか確認する。
go env
した際に出てきたgolangのディレクトリを探索していってみる。
# 自分はcdしたらlsが実行されるように関数設定してる $ cd /home/motty/.asdf/installs/golang/1.14.4/packages bin pkg src $ cd src github.com golang.org gopkg.in $ cd github.com cpuguy83 dgrijalva fatih fsnotify labstack mattn oxequa sirupsen urfave valyala
oxequa
内を確認したらrealize
あったわ。
githubのissueを漁りまくる
上のissueにもあったんですが、やっぱり$GOPATH
関連かなと思い、.bashrc
の方に追記
$ export GOPATH="$HOME/go" $ source $HOME/.bashrc $ realize _ _ ___ ___ _ __ ___ _ __ ___ __ _ _ __ __| | _ __ ___ | |_ / __/ _ \| '_ ` _ \| '_ ` _ \ / _` | '_ \ / _` | | '_ \ / _ \| __| | (_| (_) | | | | | | | | | | | (_| | | | | (_| | | | | | (_) | |_ \___\___/|_| |_| |_|_| |_| |_|\__,_|_| |_|\__,_| |_| |_|\___/ \__| __ _ / _| ___ _ _ _ __ __| | | |_ / _ \| | | | '_ \ / _` | | _| (_) | |_| | | | | (_| | |_| \___/ \__,_|_| |_|\__,_|
GOPATHじゃないっぽい。。。
とおもったらasdf-golang
を使ってrealize使えねーよって言ってる人がいた。
バージョンは違うけど、ほぼ同じ。
$ asdf reshim golang $ realize NAME: Realize - A new cli application USAGE: realize [global options] command [command options] [arguments...] VERSION: 2.0.3 DESCRIPTION: Realize is the #1 Golang Task Runner which enhance your workflow by automating the most common tasks and using the best performing Golang live reloading. COMMANDS: start, s version, v help, h Shows a list of commands or help for one command Configuration: add, a init, i remove, r clean, c GLOBAL OPTIONS: --help, -h show help (default: false) --version, -v print the version (default: false)
キターーーー。
おわり
こういうの毎回つらいので、解決はしましたがdocker image使った方が楽なのでコンテナ開発しますわ。
【vim】UltiSnips.vimを削除した際にError occurred in source's gather_candidates()!が出た時の解決方法
どうもてぃです。
react最近楽しんでやってます。
新居を買うのでそれに向けて案件取得の幅をきかせるため頑張っているんですが、vimでreactを使う際にもっと効率化を図りたかった。
その時に起こった出来事です。
プラグインを入れようとした
vim-react-snippets
を入れようとしました。
dein.vimなのでそれに対応する書き方で
" with minpac function! PackInit() abort packadd minpac call minpac#init() call minpac#add('k-takata/minpac', {'type': 'opt'}) call minpac#add('SirVer/ultisnips') call minpac#add('mlaursen/vim-react-snippets') endfunction " with vim-plug call dein#add('SirVer/ultisnips') call dein#add('mlaursen/vim-react-snippets')
これを追記。
するとpython3.8関連でエラーが出て使えませんでした。
vim --version | grep python
とするとpython3/dyn
は+
になってるんですけどね。python
は確かに-
でしたが…。これに関しては全くの謎。
インサートモードで文字を入れるだけでもめちゃくちゃロードエラーが出てなんにもできなかったので、エラーが出てたultisnips.vim
のcacheから何から全て削除することにしました。
ultisnips.vimを削除したら…
Error occurred in source's gather_candidates()!
題にあるとおりのエラーが。
調べても以下のくらいしか出ませんでした。
ちょっと今回の自分とは関係なさそう。。。
結果、解決方法
プラグイン消しただけでこの有様だったので、プラグイン全てダウンロードし直そうかと思ったんですが、その前にキャッシュを削除してみました。
:call dein#recache_runtimepath()
なんとこれで解決。
題のエラーは出なくなりました。
pythonのパッケージいれてリビルドするときまたエラーで悩まされそうだなぁ。
【雑記】steamでゲームをする際、コントローラーやカーソルが勝手に動く現象の解決方法
どうもてぃ。
初めてゲームに関する記事を公開します。
どうぞ、お手柔らかに。。。
経緯
6月末はsteamのサマーセール!
自分はこの期間を狙って欲しいゲームを買い散らかしました。
以下が購入ラインナップ。
- Bag Fables
- ダークソウルⅡ
- ダークソウルⅢ
- terraria
- バイオハザード4
- undertail
- Little Witch Nobeta
もともとダークソウルにModを入れてやりたいと思っていたので、そのついでに安くなってるゲームたちも一緒に買ってしまったというわけです。
そんな自分がゲーム意欲を無くす事件が起こるとは思いもしませんでした。。。
Bag Fablesを起動!
サマーセールで買い散らかしたと言ったのですが、実はサマーセールの前にちょっとしたセールでバイオ4・ダークソウルⅡ・Ⅲは安くなっていたのです。
なのでフォロワーさんにおすすめされたBag Fablesも含めて一緒に買ってしまいました。
その時、かなりフォロワーさんがBag Fablesに熱を入れていて、自分もチョットやってみようと思い起動に至りました。
ここでトラブル発生。
起動して「あたらしいぼうけん」を選択後、ファイル名を入力画面で、入力カーソルがずーーーーーーーーーーーーーーーーーーーーーっと左に移動し続けるのです。
コントローラー抜いてもなおりまへん。
— もてぃ@パパ筋肉先生 (@smo_t93) 2020年7月4日
マウスで起動してもだめです🙅♀#bugfables #steam pic.twitter.com/K1fWC2jrkR
steamのコントローラー設定、windowsのコントローラー設定、Xbox oneのコントローラーが(新品なのに)壊れていないか確認、などなどいろんなことを試してみたんですが結局ダメでした。
こんなことある??
特定のゲームだけっぽい?
ちょっとsteamのゲーム欲が減ってしまっていたのですが、試しにバイオ4を起動。こいつはうまく起動できる。
Little Witch Nobetaを起動。これはカーソルがずーーーーーーーーーーーーーーーーっと上に行って何も選択できない。
やる気の関係でこれくらいしか試していないんですが、特定のゲームでバグが発生しているっぽかったです。
steamさん、頼みますよ…。
その後ネットで、
- steam コントローラー 勝手に動く
- steam コントローラー外す 勝手に動く
- steam bag fables 勝手に動く
- steam cursor bug
- steam controller problem
などなど、検索しまくりましたが全く解決に至りませんでした。
解決策を発見?
ダメもとでbag fablesのスレッドを開いて、カーソルバグで検索をかけてみました。
すると…これが出てきた(確か「cursor bug」みたいに検索したはず)
If you have the same issue, you must uninstall your VJoy Driver and restart your PC.
これだ。
君が同じ現象になったら、Vjoy Driverをアンインストールしてパソコンを再起動しなきゃいけない。
だってさw
そんなことで直るわけないじゃん。haha
ものは試し。Everythingを開いて、vjoyと検索(Everythingは高速ファイル検索だよ。windows使うなら入れておいて絶対に損しないよ。)
uninstallのリンクファイルが出てくるので実行。
その後、PCを再起動し、bag fablesを起動。。。
・
・
・
・
・
・
・
・
うまくいったわ!
vjoy driverを削除したことで他のコントローラーがもしかしたらうまく動かなくなる可能性はありますが、都度インストールしていけばよいでしょう。
まとめ
コントローラーに不具合がないのに、勝手にゲーム上のカーソルが動く場合の対処法は
- vjoy driverの削除
- PCの再起動
です。
以上。
誕生日じゃないけど、欲しい物リスト。
↓
【Rails】RSpecでcontrollerを書く際、deviseのauthenticate_userに毎回弾かれるときの対処法
どうもてぃです。
お久しぶりです。皆さん元気にしてましたか?
私は最近新居を建てる契約しまして、家計は火の車確定、毎日趣味の時間を犠牲になんとかお仕事を頑張って稼いでる次第であります。
はたして、この生活も何年もつことやら…。
本題
題のとおりです。公式を参考にしても弾かれて、まともなresponseが返ってこなかったので、一日時間を無駄にしました。
そのため久しぶりの記事行き。積み記事たくさんあるんですけどね。
rspec実行時が以下の状態。
% docker-compose run --rm -e RAILS_ENV=test web bundle exec rspec ./spec/controllers/tests_controller_spec.rb Starting project_1 ... done F Failures: 1) TestsController GET show response status 200 Failure/Error: expect(response.status).to be 200 expected #<Integer:401> => 200 got #<Integer:803> => 401 Compared using equal?, which compares object identity, but expected and actual are not the same object. Use `expect(actual).to eq(expected)` if you don't care about object identity in this example. # ./spec/controllers/tests_controller_spec.rb:13:in `block (3 levels) in <top (required)>' Finished in 0.12308 seconds (files took 1.13 seconds to load) 1 example, 1 failure Failed examples: rspec ./spec/controllers/tests_controller_spec.rb:11 # TestsController GET show response status 200
一応sign_in等の設定を行っているんですが、このありさま。
以下、環境や設定について書いていきます。
環境
- docker-compose version 1.25.4, build unknown
- Docker version 19.03.6, build 369ce74a3c
- Ruby 2.5.0
- Rails 5.2.1
エラー時の設定
# spec/support/controller_macros.rb module ControllerMacros def login_user(user) @request.env['devise.mapping'] = Devise.mappings[:user] sign_in user end end
sign_in用のメソッドをモジュール化。
# spec/rails_helper . . require 'devise' require File.expand_path('./spec/support/controller_macros.rb') RSpec.configure do |config| . . . . config.expect_with :rspec do |c| c.syntax = :expect end config.include Devise::Test::ControllerHelpers, type: :controller config.include ControllerMacros, type: :controller config.include Warden::Test::Helpers . . end
devise用にrails_helperへの設定を追加。
実際にテストで使用してみる。
require 'rails_helper' RSpec.describe TestsController, type: :controller do let(:test) { create(:test) } let(:user) { test.test_category.user } let(:company) { create(:company) } describe 'GET show' do before { login_user user } it 'response status 200' do get :show, params: { id: test.id } expect(response.status).to eq 200 end end end
これを実行してみた結果が最初のエラーです。
login_userメソッドのタイミングを変えたりいろいろ試してみたんですが、結局ダメでした。
対処法
いろんな記事のものを試してみたんですが、全くうまくいかずstackoverflowに同じようなエラー出てる人がいたので、参考にして設定を追加。
以下のリンク
controller_macros.rb
とrails_helper.rb
を変更。
module ControllerMacros def login_user(user) @request.env['devise.mapping'] = Devise.mappings[:user] controller.stub(:current_user).and_return(user) sign_in(user, scope: :user) end end
. . . RSpec.configure do |config| . . . . # devise setting config.expect_with :rspec do |c| c.syntax = :expect end config.include Devise::Test::ControllerHelpers, type: :controller config.include Devise::Test::IntegrationHelpers, type: :request config.include ControllerMacros, type: :controller config.include Warden::Test::Helpers . . end
これでテストを実行すると、 設定しているauthenticate_user!
に引っかからず、controllerテストが動くようになりました。
終わりに
新居のローン返済が怖いので誰かお仕事ください。
【Vim】TypeScriptプラグイン周りでquickfixが重くなる
どうもてぃです。
皆さん日頃からvimvimしてますでしょうか?
今回直近で自社開発の別プロジェクトに参画することになったため、いい加減になってたvimのjsプラグインを整理することにしました。
まだまだ問題は山積みなんですが、その中でもLintが自動で効いて重くなる問題を先に解決することとしました。
現状
- インサートモードから出ると自動でチェックが入る
- チェック時に固まる
- 切り取り時(
x
)にもチェックが入るので作業効率が悪い - quickfixが常動くのでファイルが見にくくなる
原因究明
まずはどのプラグインが原因なのか確認。
jsやjsxでは特にこの問題は発生してなかったので、typescript関連かなと。僕の場合、typescript-vim
とtsuquyomi
しか入れてなかったためすぐに見つかりました。
原因はtsuquyomi
の方でした。
quickfixを出ないようにする
最初にやった対処がこれです。
let g:tsuquyomi_disable_quickfix = 1
これを設定すれば、quickfixがそもそもでなくなります。
が、毎回:TsuGeterr
するのは面倒くさい。マップしようかなともおもいましたが、保存時に自動で動くようにしたかった。
pull requestあった
有志の方が修正してました。マジ神。
vim8ならlet g:tsuquyomi_use_vimproc = 0
、そうでなければ autocmd InsertLeave,TextChanged,BufWritePost *.ts,*.tsx call tsuquyomi#asyncGeterr()
を設定すれば、非同期でチェックを行うので、画面が固まらなくなると。
ありがとうございます。感謝。
おわり
まだtsuquyomiでの補完も効かない問題が残ってます。
今回ので前よりは速くなったし固まらなくなったけど、ファイル修正途中で毎回動くと少しラグがな…と思ってますが、quickfixをdisableにするしかなくなるので一旦これで我慢です。
TypeScriptもっとがんばろうー。