Skip to content

Instantly share code, notes, and snippets.

@DingK-R DingK-R/gin_test.go

Last active Mar 14, 2017
Embed
What would you like to do?
gin test
package main
import (
"database/sql"
"log"
"time"
"github.com/Shopify/sarama"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
)
func main() {
gin.SetMode(gin.ReleaseMode)
router := gin.Default()
router.POST("/collect", kafka)
router.Run()
}
func simple(c *gin.Context) {
c.String(200, "Hello World!")
}
func mysql(c *gin.Context) {
db, err := sql.Open("mysql", "root:123456@tcp(0.0.0.0:33061)/test?charset=utf8&loc=Asia%2FShanghai")
if err != nil {
panic(err)
}
defer db.Close()
stmt, err := db.Prepare("insert test(test) values(?)")
if err != nil {
panic(err)
}
defer stmt.Close()
stmt.Exec("123")
}
func kafka(c *gin.Context) {
brokers := []string{"0.0.0.0:9092"}
config := sarama.NewConfig()
config.Producer.RequiredAcks = sarama.WaitForLocal
config.Producer.Compression = sarama.CompressionSnappy
config.Producer.Flush.Frequency = 500 * time.Millisecond
producer, err := sarama.NewAsyncProducer(brokers, config)
if err != nil {
panic(err)
}
defer func() {
if err := producer.Close(); err != nil {
panic(err)
}
}()
msg := &sarama.ProducerMessage{
Topic: "important_test",
Key: sarama.StringEncoder("app_hello"),
Value: sarama.StringEncoder("okokokok"),
}
producer.Input() <- msg
go func() {
for err := range producer.Errors() {
log.Println("Failed to write access log entry:", err)
}
}()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.