register.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package functions
  2. import (
  3. "io/ioutil"
  4. "bytes"
  5. "github.com/gravitl/netmaker/netclient/config"
  6. "github.com/gravitl/netmaker/netclient/wireguard"
  7. "github.com/gravitl/netmaker/models"
  8. "encoding/json"
  9. "net/http"
  10. "errors"
  11. )
  12. func Register(cfg config.GlobalConfig) error {
  13. postclient := &models.ServerClient{
  14. AccessKey: cfg.Client.AccessKey,
  15. PublicKey: cfg.Client.PublicKey,
  16. PrivateKey: cfg.Client.PublicKey,
  17. Address: cfg.Client.Address,
  18. Address6: cfg.Client.Address6,
  19. Network: "comms",
  20. }
  21. jsonstring, err := json.Marshal(postclient)
  22. if err != nil {
  23. return err
  24. }
  25. jsonbytes := []byte(jsonstring)
  26. body := bytes.NewBuffer(jsonbytes)
  27. res, err := http.Post("http:/"+cfg.Client.ServerEndpoint+"/api/register","application/json",body)
  28. if err != nil {
  29. return err
  30. }
  31. if res.StatusCode != http.StatusOK {
  32. return errors.New("request to server failed: " + res.Status)
  33. }
  34. bodyBytes, err := ioutil.ReadAll(res.Body)
  35. if err != nil {
  36. return err
  37. }
  38. var wgclient models.ServerClient
  39. json.Unmarshal(bodyBytes, &wgclient)
  40. err = config.ModGlobalConfig(wgclient)
  41. if err != nil {
  42. return err
  43. }
  44. err = wireguard.InitGRPCWireguard(wgclient)
  45. if err != nil {
  46. return err
  47. }
  48. return err
  49. }