Example #1
0
func HTTP() {
	port := os.Getenv("PORT")
	host := os.Getenv("HOST")
	if port == "" {
		port = "8000"
	}

	r := gin.Default()
	r.GET("/", func(ctx *gin.Context) {
		if dur := ctx.Query("sleep"); dur != "" {
			duration, err := time.ParseDuration(dur)
			if err != nil {
				ctx.AbortWithError(http.StatusBadRequest, err)
				return
			}
			time.Sleep(duration)
		}
		printEnvNow(ctx.Writer)
	})
	r.GET("/json", func(ctx *gin.Context) {
		ctx.File("dummy.json")
	})
	r.HEAD("/json", func(ctx *gin.Context) {
		ctx.File("dummy.json")
	})
	r.HEAD("/", func(ctx *gin.Context) {
		printEnvNow(ctx.Writer)
	})
	r.GET("/_stats", gin.WrapF(stats_api.Handler))
	r.Run(host + ":" + port)
}
Example #2
0
// NewHandler is return http.Handler
func NewHandler() http.Handler {
	router := gin.Default()

	router.GET("/", func(ctx *gin.Context) {
		ctx.String(200, "%s\n", "gopham works")
	})

	// Server-Sent Events
	router.GET("/sse", gin.WrapF(pham.SSEHandler))
	// WebSocket
	router.GET("/subscribe", gin.WrapF(pham.WSHandler))

	// post message
	router.POST("/", func(ctx *gin.Context) {
		defer func() {
			cause := recover()
			if cause != nil {
				ctx.JSON(400, gin.H{
					"status": "ng",
					"error":  cause.(error).Error(),
				})
			}
		}()

		message := new(pham.Message)
		err := ctx.BindJSON(message)
		if err != nil {
			panic(err)
		}

		if message.Channel == "" || message.Data == nil {
			ctx.JSON(400, gin.H{
				"status": "ng",
				"error":  "`channel` and `data` is required.",
			})
			return
		}

		log.Printf("server: %#v\n", message)
		data := pham.JSON{
			"channel": message.Channel,
			"ttl":     message.TTL,
			"data":    message.Data,
		}

		// encode json
		connectionLen, err := manager.Broadcast(data)
		if err != nil {
			panic(err)
		}

		ctx.JSON(200, gin.H{
			"status":      "ok",
			"connections": connectionLen,
			"message":     data,
		})
	})

	// static & middleware route
	router.Static("/static", "static")

	return router
}