github.com/line/line-bot-sdk-go/v7@v7.21.0/linebot/httphandler/httphandler.go (about) 1 // Copyright 2016 LINE Corporation 2 // 3 // LINE Corporation licenses this file to you under the Apache License, 4 // version 2.0 (the "License"); you may not use this file except in compliance 5 // with the License. You may obtain a copy of the License at: 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations 13 // under the License. 14 15 package httphandler 16 17 import ( 18 "errors" 19 "net/http" 20 21 "github.com/line/line-bot-sdk-go/v7/linebot" 22 ) 23 24 // EventsHandlerFunc type 25 type EventsHandlerFunc func([]*linebot.Event, *http.Request) 26 27 // ErrorHandlerFunc type 28 type ErrorHandlerFunc func(error, *http.Request) 29 30 // WebhookHandler type 31 type WebhookHandler struct { 32 channelSecret string 33 channelToken string 34 35 handleEvents EventsHandlerFunc 36 handleError ErrorHandlerFunc 37 } 38 39 // New returns a new WebhookHandler instance. 40 func New(channelSecret, channelToken string) (*WebhookHandler, error) { 41 if channelSecret == "" { 42 return nil, errors.New("missing channel secret") 43 } 44 if channelToken == "" { 45 return nil, errors.New("missing channel access token") 46 } 47 h := &WebhookHandler{ 48 channelSecret: channelSecret, 49 channelToken: channelToken, 50 } 51 return h, nil 52 } 53 54 // HandleEvents method 55 func (wh *WebhookHandler) HandleEvents(f EventsHandlerFunc) { 56 wh.handleEvents = f 57 } 58 59 // HandleError method 60 func (wh *WebhookHandler) HandleError(f ErrorHandlerFunc) { 61 wh.handleError = f 62 } 63 64 // NewClient method 65 func (wh *WebhookHandler) NewClient(options ...linebot.ClientOption) (*linebot.Client, error) { 66 return linebot.New(wh.channelSecret, wh.channelToken, options...) 67 } 68 69 func (wh *WebhookHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { 70 events, err := linebot.ParseRequest(wh.channelSecret, r) 71 if err != nil { 72 if wh.handleError != nil { 73 wh.handleError(err, r) 74 } 75 if err == linebot.ErrInvalidSignature { 76 w.WriteHeader(400) 77 } else { 78 w.WriteHeader(500) 79 } 80 return 81 } 82 wh.handleEvents(events, r) 83 }