LoginSignup
1

More than 5 years have passed since last update.

[golang]FCMの単一端末に通知を送る

Last updated at Posted at 2017-05-14

手元で動かしただけなので特にGAEとかで検証はしてない。

package main

import (
    "bytes"
    "encoding/json"
    "net/http"
)

func main() {
    PostToFCM(
        "##FIRInstanceID.instanceID().token()##",
        "hello",
    )
}

type FCMParams struct {
    To           string          `json:"to"`
    Notification FCMNotification `json:"notification"`
    Priority     int             `json:"priority"`
}
type FCMNotification struct {
    Body string `json:"body"`
}

func PostToFCM(to string, body string) error {
    n := FCMNotification{
        Body: body,
    }
    params := &FCMParams{
        To:           to,
        Notification: n,
        Priority:     10,
    }
    b, err := json.Marshal(params)
    jsonStr := string(b)

    req, err := http.NewRequest(
        "POST",
        "https://fcm.googleapis.com/fcm/send",
        bytes.NewBuffer([]byte(jsonStr)),
    )
    if err != nil {
        return err
    }

    // Content-Type 設定
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", "key=##FCMのサーバーキー##")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return err
    }
    defer resp.Body.Close()

    return err
}

とりまこんな感じ。

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
1