github.com/line/line-bot-sdk-go/v7@v7.21.0/examples/echo_bot_handler/server.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 main
    16  
    17  import (
    18  	"log"
    19  	"net/http"
    20  	"os"
    21  
    22  	"github.com/line/line-bot-sdk-go/v7/linebot"
    23  	"github.com/line/line-bot-sdk-go/v7/linebot/httphandler"
    24  )
    25  
    26  func main() {
    27  	handler, err := httphandler.New(
    28  		os.Getenv("CHANNEL_SECRET"),
    29  		os.Getenv("CHANNEL_TOKEN"),
    30  	)
    31  	if err != nil {
    32  		log.Fatal(err)
    33  	}
    34  
    35  	// Setup HTTP Server for receiving requests from LINE platform
    36  	handler.HandleEvents(func(events []*linebot.Event, r *http.Request) {
    37  		bot, err := handler.NewClient()
    38  		if err != nil {
    39  			log.Print(err)
    40  			return
    41  		}
    42  		for _, event := range events {
    43  			if event.Type == linebot.EventTypeMessage {
    44  				switch message := event.Message.(type) {
    45  				case *linebot.TextMessage:
    46  					if _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(message.Text)).Do(); err != nil {
    47  						log.Print(err)
    48  					}
    49  				}
    50  			}
    51  		}
    52  	})
    53  	http.Handle("/callback", handler)
    54  	// This is just a sample code.
    55  	// For actually use, you must support HTTPS by using `ListenAndServeTLS`, reverse proxy or etc.
    56  	if err := http.ListenAndServe(":"+os.Getenv("PORT"), nil); err != nil {
    57  		log.Fatal(err)
    58  	}
    59  }