Пример #1
0
func sendInquiry(c web.C, w http.ResponseWriter, r *http.Request) {

	formData := make(map[string][]string)
	if err := r.ParseForm(); err != nil {
		panic("parse error")
	} else {
		formData = r.PostForm
	}
	pp.Println(formData)

	session, _ := store.Get(r, "inqury")
	session.Values["message"] = "send inquery"

	buf := new(bytes.Buffer)
	gob.Register(map[string][]string{})
	enc := gob.NewEncoder(buf)
	if err := enc.Encode(&formData); err != nil {
		pp.Println(err)
	}
	session.Values["formData"] = formData
	if err := session.Save(r, w); err != nil {
		pp.Println(err)
	}

	http.Redirect(w, r, "/", http.StatusFound)
}
Пример #2
0
// 顧客情報を保存します。
func SaveCustomer(customer *Customer) (*Customer, error) {
	db, err := common.GetDB()
	if err != nil {
		panic(err.Error())
	}
	defer db.Close()

	pp.Println(customer)

	var existCustomer Customer
	db.Where("ID = ?", customer.ID).First(&existCustomer)

	pp.Println(existCustomer)

	if existCustomer.ID != "" {
		// 更新
		customer.UpdatedAt = time.Now()
		db.Model(&customer).Where("ID = ?", customer.ID).Update(customer)
	} else {
		// 新規登録
		customer.ID = uuid.NewV4().String()
		customer.CreatedAt = time.Now()
		db.Create(&customer)
	}

	return customer, err
}
Пример #3
0
func inquiry(c web.C, w http.ResponseWriter, r *http.Request) {
	if tpl, err := pongo2.DefaultSet.FromFile("inquiry.tpl"); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	} else {
		session, _ := store.Get(r, "inqury")
		message := ""
		msg := session.Values["message"]
		_, ok := msg.(string)
		if ok {
			message = msg.(string)
			session.Values["message"] = nil
			session.Save(r, w)
		}

		bytes, err := tpl.ExecuteBytes(pongo2.Context{"title": "inquiry", "message": message})
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
		formData := session.Values["formData"]
		if formData != nil {
			pp.Println(formData)
			bytes = fillinform.Fill(bytes, formData.(map[string][]string), nil)
			session.Values["formData"] = nil
			if err := session.Save(r, w); err != nil {
				pp.Println(err)
			}
		}
		w.Write(bytes)
	}
}
Пример #4
0
func (c ChatServerClientSlack) Say(ch string, msg string) {
	pp.Println(ch, msg)
	title := "alert"
	// 引用でおくるとき
	_, err := json.Marshal(&payload{Attachments: []*attachment{
		&attachment{
			Fallback: title,
			Pretext:  title,
			Fields: []*field{
				&field{
					Title: "",
					Value: msg,
					Short: false,
				},
			},
		},
	},
	})
	// フラットなテキスト + channel override
	p, err := json.Marshal(&textPayload{Text: msg, Channel: ch})
	res, err := http.PostForm(c.WebHookURL, url.Values{"payload": []string{string(p)}})
	if err != nil {
		log.Println("error on slack")
	}
	if res.StatusCode != 200 {
		pp.Println(res.Status)
	}
}
Пример #5
0
func PayPalPaymentExecute(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	pp.Println(r.Header)
	pp.Println(r.Cookies())

	buf := bytes.NewBufferString(fmt.Sprintf("{ \"payer_id\" : \"%s\"}", r.FormValue("PayerID")))
	req, err := http.NewRequest("POST", fmt.Sprintf("https://api.sandbox.paypal.com/v1/payments/payment/%s/execute/", r.FormValue("paymentId")), buf)
	if err != nil {
		log.Fatalln(err)
		renderer.JSON(w, 400, err.Error())
		return
	}
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Authorization", fmt.Println("Bearer %s", authToken))

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatalln(err)
		renderer.JSON(w, 400, err.Error())
		return
	}
	defer res.Body.Close()

	data, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Fatalln(err)
		renderer.JSON(w, 400, err.Error())
		return
	}

	fmt.Println(string(data))

	http.Redirect(w, r, "/payment/done", 302)
}
Пример #6
0
func main() {
	cfg := NewConfig()

	if err := cfg.Load("config.json"); err != nil {
		log.Printf("[ERROR] %+v", err)
		return
	}
	defer func() {
		if err := cfg.Save(); err != nil {
			log.Printf("[ERROR] %+v", err)
			return
		}
	}()

	if len(cfg.Ips) > 100 {
		for k, v := range cfg.Ips {
			cfg.DeleteIp(k)
			log.Printf("Delete IP %s: %s", k, v)
			break
		}
	}

	fake.SetLang("ru")
	ipParams := cfg.SetIp(fake.IPv4(), true)
	ipParams.Description = fake.FullName()
	ipParams.SetExpire(time.Now().Add(time.Minute))

	pp.Println(cfg.AllowIp("181.113.250.128"))
	pp.Println(cfg.AllowIp("89.155.206.159"))
}
Пример #7
0
func apiCall(method string, params url.Values, callback func([]byte)) error {
	params.Set("token", SLACK_TOKEN)

	u := SLACK_API_URL + method
	res, err := http.PostForm(u, params)
	pp.Println(res.Request)
	pp.Println(res.Header)
	if err != nil {
		if data, err := createErrorResponse(res.StatusCode); err != nil {
			return err
		} else {
			callback(data)
		}
	}

	pp.Println(res.StatusCode)

	if res.StatusCode == http.StatusOK {
		if resData, err := ioutil.ReadAll(res.Body); err != nil {
			return err
		} else {
			callback(resData)
		}
	} else {
		if data, err := createErrorResponse(res.StatusCode); err != nil {
			return err
		} else {
			callback(data)
		}
	}
	return nil
}
Пример #8
0
func (conn *Connection) Loop() {
	for {
		ws, err := conn.newWSConnection()
		if err != nil {
			log.Fatal(err)
		}
		defer ws.Close()
		ws.SetDeadline(time.Now().Add(10 * time.Minute))

		func() {
			for {
				data := json.RawMessage{}
				if err := websocket.JSON.Receive(ws, &data); err != nil {
					log.Printf("failed websocket json receive: %v", err)
					return
				}

				event := &Type{}
				if err := json.Unmarshal(data, event); err != nil {
					log.Printf("failed json unmarshal: %v", err)
					continue
				}

				v, ok := eventMapping[event.Type]
				if !ok {
					continue
				}

				typeOf := reflect.TypeOf(v)
				ep := reflect.New(typeOf).Interface()
				if err := json.Unmarshal(data, ep); err != nil {
					log.Printf("failed json unmarshal for type: %v", err)
					continue
				}

				switch e := ep.(type) {
				case *HelloEvent:
					// ...
				case *MessageEvent:
					conn.CallCb(*e)
				case *ChannelCreatedEvent:
					conn.channelMap[e.Channel.Id] = e.Channel.Name
					pp.Println(conn.channelMap)
				case *ChannelDeletedEvent:
					delete(conn.channelMap, e.Channel)
					pp.Println(conn.channelMap)
				case *ChannelRenameEvent:
					conn.channelMap[e.Channel.Id] = e.Channel.Name
					pp.Println(conn.channelMap)
				case *UserChangeEvent:
					conn.userMap[e.User.Id] = e.User.Name
					pp.Println(conn.userMap)
				default:
				}
			}
		}()
	}

}
Пример #9
0
func PaymentDone(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	pp.Println(r.Form)
	pp.Println(r.Header)
	pp.Println(r.Cookies())

	w.Write([]byte("OK"))
}
Пример #10
0
func TestQueryMemoryCache(t *testing.T) {
	s := New()
	defer s.Close()
	q := s.QueryMemoryCache(testQuery, testArgs...)
	pp.Println(q)

	q = s.QueryMemoryCache(testQuery, testArgs...)
	pp.Println(q)
}
Пример #11
0
func TestQueryKVSCache(t *testing.T) {
	s := New()
	defer s.Close()
	cacheKey := fmt.Sprintf("%s:%v", testQuery, testArgs)
	s.KVS.Del(cacheKey)

	q := s.QueryKVSCache(testQuery, testArgs...)
	pp.Println(q)

	q = s.QueryKVSCache(testQuery, testArgs...)
	pp.Println(q)
}
Пример #12
0
func main() {
	fmt.Println("Hello world!")
	err := getError()
	err = errors.Wrap(err, "open failed")
	err = subErr(err)
	err = errors.Wrap(err, "read config failed")

	pp.Println("Cause: ", errors.Cause(err))
	err = errors.Wrap(err, "New message")
	pp.Println("Error: ", err)
	fmt.Printf("[%+v]\n", err)
	fmt.Printf("{%+v}\n", errors.Cause(err))
	fmt.Printf("[%v]\n", err)
}
Пример #13
0
func DebugDump(v ...interface{}) {
	if IsDebugging() {
		for _, r := range v {
			pp.Println(r)
		}
	}
}
Пример #14
0
func itemHandler(feed *rss.Feed, ch *rss.Channel, newitems []*rss.Item) {
	fmt.Println("itemHandler")
	fmt.Println(len(newitems), "new item(s) in", ch.Title, "of", feed.Url)
	for _, item := range newitems {
		pp.Println(item)
	}
}
Пример #15
0
func main() {
	// Init loggers
	scenariolib.InitLogger(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr)

	// Seed Random based on current time
	source := rand.NewSource(int64(time.Now().Unix()))
	random := rand.New(source)

	searchToken := os.Getenv("SEARCHTOKEN")
	analyticsToken := os.Getenv("UATOKEN")
	if searchToken == "" || analyticsToken == "" {
		scenariolib.Error.Println("SEARCHTOKEN, UATOKEN need to be defined as env variables")
	}

	scenarioURL := os.Getenv("SCENARIOSURL")
	if scenarioURL == "" {
		scenariolib.Error.Println("SCENARIOSURL env variable needs to define a file path")
	}

	local := os.Getenv("LOCAL") == "true"
	if local {
		scenariolib.Info.Println("STARTING IN LOCAL MODE, MAKE SURE THE SCENARIOSURL IS A LOCAL PATH")
	}

	bot := scenariolib.NewUabot(local, scenarioURL, searchToken, analyticsToken, random)

	quit := make(chan bool)
	err := bot.Run(quit)
	if err != nil {
		scenariolib.Error.Println(err)
	}
	pp.Println("LOG >>> DONE")
}
Пример #16
0
func chanHandler(feed *rss.Feed, newchannels []*rss.Channel) {
	fmt.Println("chanHandler")
	fmt.Println(len(newchannels), "new channel(s) in", feed.Url)
	for _, c := range newchannels {
		pp.Println(c)
	}
}
Пример #17
0
func main() {
	var err error

	ta := &data.Users{}
	ta.Users = []data.Item{
		{1, "John", "123"},
		{2, "Bob", "123"},
		{3, "Mary", "123"},
		{4, "Dave", "123"},
		{5, "Ken", "123"},
	}

	log.Println("Marshal default")
	str, err := json.Marshal(ta)
	chk(err)
	fmt.Println(string(str))

	log.Println("Marshal ffjson")
	str2, err := ta.MarshalJSON()
	chk(err)
	fmt.Println(string(str2))

	log.Println("Unmarshal array")
	json_str := `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]`
	a := make([]Item, 0)

	err = json.Unmarshal([]byte(json_str), &a)
	chk(err)
	pp.Println(a)

}
Пример #18
0
func DumpAST(body string) {
	scanner := new(parsing.Scanner)
	scanner.Init([]rune(body), 0)
	defs := parsing.Parse(scanner)

	pp.Println(defs)
}
Пример #19
0
func DumpIR1(defs []Def) {
	err, intMods := astToIr1(defs)
	if err != nil {
		log.Fatal("Conversion error: ", err)
	}
	pp.Println(intMods)
}
Пример #20
0
func main() {
	c := table.New(azure.StorageCredentials{
		AccountName: os.Getenv("AZURE_STORAGE_ACCOUNT_NAME"),
		AccessKey:   os.Getenv("AZURE_STORAGE_ACCESS_KEY"),
	})
	c.Debug = true

	err := c.Create("messages")
	if err != nil {
		fmt.Println(err)
	}

	err = c.Insert("messages", Message{
		Body:         "My message body!",
		RowKey:       "1",
		PartitionKey: "network-1",
	})
	if err != nil {
		fmt.Println(err)
	}

	m := &Message{}
	err = c.GetEntity(table.RowQuery{
		Table:        "messages",
		PartitionKey: "network-1",
		RowKey:       "1",
		Fields:       []string{"Body", "RowKey", "PartitionKey"},
	}, m)

	if err != nil {
		fmt.Println(err)
	}

	pp.Println(m)
}
Пример #21
0
func TestTrieOptimizer_Compile(t *testing.T) {
	to := regexp.NewTrieOptimizer()
	to.Add("hoge")
	to.Add("fuga")
	to.Add("piyo")
	if to.Re() != "(?:fuga|hoge|piyo)" {
		t.Errorf("%s vs (?:fuga|hoge|piyo)", to.Re())
	}

	to = regexp.NewTrieOptimizer()
	to.Add("public")
	to.Add("private")
	to.Add("pipip.$")
	if to.Re() != "p(?:ipip\\.\\$|rivate|ublic)" {
		t.Errorf("%s vs p(?:ipip\\.\\$|rivate|ublic)", to.Re())
	}

	to = regexp.NewTrieOptimizer()
	if to.Re() != "^\\b\x00" {
		t.Errorf("%s vs ^\\b\x00", to.Re())
	}

	to = regexp.NewTrieOptimizer()
	to.Add("sun")
	to.Add("sunw")
	to.Add("org")
	pp.Println(to)
	if to.Re() != "(?:org|sunw?)" {
		t.Errorf("%s vs (?:org|sunw?)", to.Re())
	}
}
Пример #22
0
func UpdateDB(title string) error {
	cfg.GetLogger().Info("Trying to update", "DB", title)

	var dbData cfg.DB
	var ok bool
	if dbData, ok = cfg.GetConfig().GetDBByTitle(title); !ok {
		return setDBStatusFailed(title, "Failed to get db data from config")
	}

	adapter, err := adapter.New(dbData)
	if err != nil {
		return err
	}
	tables, err := adapter.ListTables()
	if err != nil {
		return err
	}
	for _, table := range tables {
		table.State, err = adapter.GetState(table)
		if err != nil {
			return err
		}

		cfg.GetLogger().Debug("Got table status", "table", table, "filling", fmt.Sprintf("%.10f", table.State.Filling))
		if cfg.GetConfig().Debug {
			pp.Println(table)
		}
	}

	return err
}
Пример #23
0
func main() {
	proxies, err := proxy.CyberSource()
	if err != nil {
		log.Fatal(err)
	}
	pp.Println(proxies)
}
Пример #24
0
func init() {
	log.Print("Generate password hashes")
	Users["user"], _ = getHash("hello")
	Users["john"], _ = getHash("hello")
	Users["bill"], _ = getHash("hello")
	Users["max"], _ = getHash("hello")
	pp.Println(Users)
}
Пример #25
0
func main() {
	fk := flipkart.Flipkart{
		AffiliateId:   os.Getenv("FK_ID"),
		AffliateToken: os.Getenv("FK_TOKEN"),
		Host:          "",
	}

	resp, err := fk.ProductFeeds()
	if err == nil {
		pp.Println(resp)
	} else {
		fmt.Printf("Error occurred: %s\n", err.Error())
	}

	// Get a product by ID
	pr, err := fk.Get("MOBE6KK93JG5WKB2")
	if err == nil {
		pp.Println(pr)
	} else {
		fmt.Printf("Error occurred: %s\n", err.Error())
	}

	// Search for a product by keyword
	prs, err := fk.Search("leather wallet", 200)
	if err == nil {
		pp.Println(prs)
	} else {
		fmt.Printf("Error occured: %s\n", err.Error())
	}

	// Get Deal of the Day Offers
	offers, err := fk.DOTDOffers()
	if err == nil {
		pp.Println(offers)
	} else {
		fmt.Printf("Error occurred: %s\n", err.Error())
	}

	// Get Top offers
	top, err := fk.TopOffers()
	if err == nil {
		pp.Println(top)
	} else {
		fmt.Printf("Error occurred: %s\n", err.Error())
	}
}
Пример #26
0
func route(fn func(http.ResponseWriter, *http.Request, string), basePath string) http.HandlerFunc {
	pp.Println("basePath =", basePath)

	return func(w http.ResponseWriter, r *http.Request) {
		key := r.URL.Path[len(basePath):]
		fn(w, r, key)
	}
}
func editCity(w http.ResponseWriter, r *http.Request, id int) {
	c := &city{Id: id}
	pp.Println("c =", c)

	err := c.read()
	if err != nil {
		fmt.Println(err)
		httpGenericErr(w)
		return
	}
	pp.Println("c =", c)

	if isAPIPath(r.URL.Path) {
		renderJSON(w, c)
	} else {
		renderHTML(w, c, "cities/edit")
	}
}
Пример #28
0
func (p *PullRequestsService) buildPullRequestBody(po *PullRequestsOptions) string {

	body := map[string]interface{}{}
	body["source"] = map[string]interface{}{}
	body["destination"] = map[string]interface{}{}
	body["reviewers"] = []map[string]string{}
	body["title"] = ""
	body["description"] = ""
	body["message"] = ""
	body["close_source_branch"] = false

	if n := len(po.Reviewers); n > 0 {
		for i, user := range po.Reviewers {
			body["reviewers"].([]map[string]string)[i] = map[string]string{"username": user}
		}
	}

	if po.Source_branch != "" {
		body["source"].(map[string]interface{})["branch"] = map[string]string{"name": po.Source_branch}
	}

	if po.Source_repository != "" {
		body["source"].(map[string]interface{})["repository"] = map[string]interface{}{"full_name": po.Source_repository}
	}

	if po.Destination_branch != "" {
		body["destination"].(map[string]interface{})["branch"] = map[string]interface{}{"name": po.Destination_branch}
	}

	if po.Destination_commit != "" {
		body["destination"].(map[string]interface{})["commit"] = map[string]interface{}{"hash": po.Destination_commit}
	}

	if po.Title != "" {
		body["title"] = po.Title
	}

	if po.Description != "" {
		body["description"] = po.Description
	}

	if po.Message != "" {
		body["message"] = po.Message
	}

	if po.Close_source_branch == true || po.Close_source_branch == false {
		body["close_source_branch"] = po.Close_source_branch
	}

	data, err := json.Marshal(body)
	if err != nil {
		pp.Println(err)
		os.Exit(9)
	}

	return string(data)
}
Пример #29
0
func main() {
	flag.Parse()
	if *DEBUG {
		logrus.SetLevel(logrus.DebugLevel)
	}
	pixiv, err := NewFromConfigFile("private/config.json")
	if err != nil {
		panic(err)
	}
	ranking, err := pixiv.Ranking("all", "daily", 50, nil, 1)
	if err != nil {
		panic(err)
	}
	for _, item := range ranking {
		if item.Work.PageCount > 1 {
			pp.Println(item)
			fullFirst, err := item.Work.Fill(pixiv)
			if err != nil {
				panic(err)
			}
			pp.Println(fullFirst)
			break
		}
	}
	//first := ranking[0].Work
	//search, err := pixiv.Search("チノ", 1)
	//if err != nil {
	//	panic(err)
	//}
	//first := search[0]
	//pp.Println(first)
	//img, err := first.OpenImage(pixiv, SIZE_LARGE, 1)
	//if err != nil {
	//	panic(err)
	//}
	//defer img.Close()
	//dst, err := os.Create(fmt.Sprintf("/Users/saki/table/sample.%s", first.Extension()))
	//if err != nil {
	//	panic(err)
	//}
	//defer dst.Close()
	//io.Copy(dst, img)
}
Пример #30
0
// Inspect will show the information about a system, pretty printed.
func Inspect(c *cli.Context) error {
	conf := config.New()
	sys, err := systems.LoadSystem(conf, c.Args().First())
	if err != nil {
		fmt.Println("Couldn't find system:", c.Args().First())
		return err
	}

	pp.Println(sys)
	return nil
}