예제 #1
0
func main() {
	defer mustbe.Catched(func(err error) { log.Fatalln("Fatal error:", err) })

	var (
		botToken   string
		apiHost    string
		dbFileName string
	)

	flag.StringVar(&botToken, "token", "", "telegram bot token")
	flag.StringVar(&apiHost, "apihost", "freefeed.net", "backend API host")
	flag.StringVar(&dbFileName, "dbfile", "", "database file name")
	flag.Parse()

	if botToken == "" || dbFileName == "" {
		flag.Usage()
		return
	}

	db := mustbe.OKVal(bolt.Open(dbFileName, 0600, &bolt.Options{Timeout: 1 * time.Second})).(*bolt.DB)
	defer db.Close()

	mustbe.OK(db.Update(func(tx *bolt.Tx) error {
		mustbe.OKVal(tx.CreateBucketIfNotExists(StatesBucket))
		return nil
	}))

	bot := mustbe.OKVal(tgbotapi.NewBotAPI(botToken)).(*tgbotapi.BotAPI)

	u := tgbotapi.NewUpdate(0)
	u.Timeout = 60

	updates, err := bot.GetUpdatesChan(u)
	if err != nil {
		log.Fatalln("Can not get update chan:", err)
		return
	}

	log.Println("Starting bot", bot.Self.UserName)

	app := &App{
		db:      db,
		apiHost: apiHost,
		outbox:  make(chan tgbotapi.Chattable, 0),
		rts:     make(map[int]*Realtime),
		cache:   gcache.New(1000).ARC().Build(),
	}

	app.LoadRT()

	for {
		select {
		case update := <-updates:
			go app.HandleMessage(&update.Message)
		case msg := <-app.outbox:
			bot.Send(msg)
		}
	}
}
예제 #2
0
func ExampleOKVal() {
	defer mustbe.Catched(func(err error) {
		fmt.Println("Catched", err)
	})

	divide := func(x, y int) (int, error) {
		if y == 0 {
			return 0, errors.New("division by zero")
		}
		return x / y, nil
	}

	fmt.Println("4 / 2 =", mustbe.OKVal(divide(4, 2)).(int))
	fmt.Println("4 / 0 =", mustbe.OKVal(divide(4, 0)).(int)) // will not be printed

	// Output: 4 / 2 = 2
	// Catched division by zero
}
예제 #3
0
파일: main.go 프로젝트: davidmz/frf-aprx
func (a *App) Handler(w http.ResponseWriter, r *http.Request) {
	defer mustbe.Catched(func(err error) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusBadRequest)
		json.NewEncoder(w).Encode(H{"err": err.Error(), "from": "aprx"})
	})

	// request path: /frf-domain/api-path
	pp := strings.SplitN(r.URL.Path, "/", 3)[1:]
	mustbeTrue(len(pp) == 2, "Invalid request path")
	domain, path := pp[0], "/"+pp[1]

	domainFound := false
	for _, d := range a.FRFDomains {
		if d == domain {
			domainFound = true
			break
		}
	}
	mustbeTrue(domainFound, "Invalid frf domain")

	var (
		accessToken    string
		frfRequestBody []byte
	)

	switch r.Header.Get("Content-Type") {
	case "application/x-www-form-urlencoded":
		r.ParseForm()
		accessToken = r.PostForm.Get("accessToken")
		r.PostForm.Del("accessToken")
		frfRequestBody = []byte(r.PostForm.Encode())

	case "application/json", "application/json; charset=utf-8":
		h := make(H)
		mustbe.OK(json.NewDecoder(r.Body).Decode(h))
		accessToken = h["accessToken"].(string)
		delete(h, "accessToken")
		frfRequestBody = mustbe.OKVal(json.Marshal(h)).([]byte)
	}

	req, err := http.NewRequest(
		r.Method,
		"https://"+domain+path,
		bytes.NewReader(frfRequestBody),
	)
	mustbe.OK(err)

	for _, h := range HeadersFromClient {
		if hh, ok := r.Header[h]; ok {
			req.Header[h] = hh
		}
	}

	if accessToken != "" {
		req.Header.Set("X-Authentication-Token", accessToken)
	}

	resp, err := http.DefaultClient.Do(req)
	mustbe.OK(err)

	defer resp.Body.Close()

	for _, h := range HeadersFromBackend {
		if hh, ok := resp.Header[h]; ok {
			w.Header()[h] = hh
		}
	}

	w.WriteHeader(resp.StatusCode)
	io.Copy(w, resp.Body)
}