1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| package main
import ( "fmt" _ "github.com/joho/godotenv/autoload" "github.com/memochou1993/line-notify-go/app" "os"
"html/template" "log" "math/rand" "net/http" "net/url" )
var ( clientID string clientSecret string callbackURL string token string )
func main() { clientID = os.Getenv("CLIENT_ID") clientSecret = os.Getenv("CLIENT_SECRET") callbackURL = os.Getenv("CALLBACK_URL")
http.HandleFunc("/callback", callbackHandler) http.HandleFunc("/notify", notifyHandler) http.HandleFunc("/auth", authHandler)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", os.Getenv("APP_PORT")), nil)) }
func callbackHandler(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { log.Println(err.Error()) }
data := url.Values{} data.Add("grant_type", "authorization_code") data.Add("code", r.Form.Get("code")) data.Add("redirect_uri", callbackURL) data.Add("client_id", clientID) data.Add("client_secret", clientSecret)
payload, err := app.Call("POST", "https://notify-bot.line.me/oauth/token", data, "")
if err != nil { log.Println(err.Error()) }
res := app.Parse(payload)
token = res.AccessToken
if _, err := w.Write(payload); err != nil { log.Println(err.Error()) } }
func notifyHandler(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { log.Println(err.Error()) }
data := url.Values{} data.Add("message", r.Form.Get("message"))
payload, err := app.Call("POST", "https://notify-api.line.me/api/notify", data, token)
if err != nil { log.Println(err.Error()) }
res := app.Parse(payload)
token = res.AccessToken
if _, err := w.Write(payload); err != nil { log.Println(err.Error()) } }
func authHandler(w http.ResponseWriter, r *http.Request) { var tmpl = template.Must(template.ParseFiles("templates/auth.html"))
err := tmpl.Execute(w, struct { ClientID string CallbackURL string State int }{ ClientID: clientID, CallbackURL: callbackURL, State: rand.Int(), })
if err != nil { log.Println(err.Error()) } }
|