ETRI_SMARTFARM_POC/containers/devicemanagera/main.go

69 lines
1.1 KiB
Go
Raw Permalink Normal View History

2021-11-16 12:28:52 +00:00
package main
import (
"bytes"
"devicemanagera/router"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"strings"
)
var server_addr string
func getIP() string {
host, _ := os.Hostname()
addrs, _ := net.LookupIP(host)
return addrs[0].String()
}
2021-11-25 01:11:47 +00:00
2021-11-16 12:28:52 +00:00
func registerToServer() {
var exist bool
server_addr, exist = os.LookupEnv("SERVER_ADDR")
if !exist {
fmt.Println("Please set SERVER_ADDR as environment variable")
}
ip := getIP()
idx := strings.LastIndex(ip, ".")
serverAddr := ip[:idx+1] + "1"
fmt.Println(serverAddr)
var obj map[string]string = make(map[string]string)
obj["name"] = "devicemanagera"
obj["addr"] = getIP() + ":3000"
b, err := json.Marshal(obj)
if err != nil {
panic(err)
}
req, err := http.NewRequest("PUT", "http://"+serverAddr+":3000/services", bytes.NewBuffer(b))
if err != nil {
panic(err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
b, err = ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Println(string(b))
// http.Post("")
}
func main() {
registerToServer()
err := http.ListenAndServe(":3000", router.NewRouter())
if err != nil {
panic(err)
}
}