github.com/stampzilla/stampzilla-go@v2.0.0-rc9+incompatible/pkg/hueemulator/handler.go (about)

     1  package hueemulator
     2  
     3  import (
     4  	"io"
     5  	"io/ioutil"
     6  	"log"
     7  	"net"
     8  	"net/http"
     9  	"os"
    10  	"sync"
    11  
    12  	"github.com/gin-gonic/gin"
    13  )
    14  
    15  var handlerMap map[int]*huestate
    16  var debug bool
    17  var handlerMapLock sync.Mutex
    18  
    19  func init() {
    20  	log.SetOutput(ioutil.Discard)
    21  	handlerMap = make(map[int]*huestate)
    22  	upnpTemplateInit()
    23  }
    24  
    25  func SetLogger(w io.Writer) {
    26  	log.SetOutput(w)
    27  }
    28  
    29  func SetDebug(d bool) {
    30  	debug = d
    31  }
    32  
    33  func ListenAndServe(addr string) error {
    34  	log.Println("Listening to: ", addr)
    35  	//router := httprouter.New()
    36  	//router := gin.Default()
    37  	router := gin.New()
    38  
    39  	if debug {
    40  		router.Use(gin.Logger())
    41  	}
    42  	router.Use(gin.Recovery())
    43  
    44  	router.GET(upnp_uri, upnpSetup(addr))
    45  
    46  	router.GET("/api/:userId/lights", getLightsList)
    47  	router.PUT("/api/:userId/lights/:lightId/state", setLightState)
    48  	router.GET("/api/:userId/lights/:lightId", getLightInfo)
    49  	router.POST("/api", func(c *gin.Context) {
    50  		defer c.Request.Body.Close()
    51  		body, err := ioutil.ReadAll(c.Request.Body)
    52  		if err != nil {
    53  			log.Println(err)
    54  		}
    55  		log.Println(string(body))
    56  		c.Writer.WriteString(`[{"success":{"username": "83b7780291a6ceffbe0bd049104df"}}]`)
    57  	})
    58  
    59  	go upnpResponder(addr, upnp_uri)
    60  	return http.ListenAndServe(addr, requestLogger(router))
    61  }
    62  
    63  // Handler:
    64  // 	state is the state of the "light" after the handler function
    65  //  if error is set to true echo will reply with "sorry the device is not responding"
    66  type Handler func(Request) error
    67  
    68  func Handle(id int, deviceName string, h Handler) {
    69  	log.Println("[HANDLE]", deviceName)
    70  	handlerMapLock.Lock()
    71  	handlerMap[id] = &huestate{
    72  		Handler: h,
    73  		Light:   initLight(id, deviceName),
    74  		Id:      id,
    75  	}
    76  	handlerMapLock.Unlock()
    77  }
    78  
    79  func requestLogger(h http.Handler) http.Handler {
    80  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    81  		if debug {
    82  			log.Println("[WEB]", r.RemoteAddr, r.Method, r.URL)
    83  		}
    84  		h.ServeHTTP(w, r)
    85  	})
    86  }
    87  func GetPrimaryIp() string {
    88  	addrs, err := net.InterfaceAddrs()
    89  	if err != nil {
    90  		os.Stderr.WriteString("Oops: " + err.Error() + "\n")
    91  		os.Exit(1)
    92  	}
    93  
    94  	for _, a := range addrs {
    95  		if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
    96  			if ipnet.IP.To4() != nil {
    97  				return ipnet.IP.String()
    98  			}
    99  		}
   100  	}
   101  	return ""
   102  }