LoginSignup
4
4

More than 5 years have passed since last update.

Angular のログサーバーを Go でサクッと作る

Posted at

はじめに

  • Angular での開発中にログを出したいが ng serve の出力にそのまま出す方法がなさそうだった。
  • window の unload イベント中の処理のログが欲しかったので console.log だと難しそう。
  • ということで Go でリクエストを表示するだけの http サーバーを立ち上げて使ってみる。

コード

  • ほとんど普通に net/http サーバーを実行してリクエストを表示するだけ
  • サーバーとクライアント共にローカルで実行するが、ポートが異なり別ホスト扱いになるので、CORS できるように github.com/rs/cors でハンドラをラップする
server.go
package main

import (
  "net/http"
  "log"
  "io/ioutil"
  "github.com/rs/cors"
)

func main() {
  handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    b, err := ioutil.ReadAll(r.Body)
    log.Printf("BODY: %+v, ERROR: %+v", string(b), err)
  })
  log.Fatal(http.ListenAndServe(":8080", cors.Default().Handler(handler)))
}

ログサーバーの実行

go run server.go

Angular でログの送信

  • 任意の Component でログを送信する
  • Http クライアントを利用するためドキュメントにしたがって app.module.ts@NgModuleimports パラメータに HttpClientModule を追加して DI できるようにしておく

// 任意の Component
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  // ログ送信用の HttpClient 初期化
  constructor(private http: HttpClient) {
  }

  @HostListener('window:unload', [ '$event' ])
  unloadHandler(event) {
    // ログ送信実行
    this.http.post("http://localhost:8080", {message: 'App Component unload'}).subscribe();
  }
}
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4