reload.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2018 fatedier, [email protected]
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package sub
  15. import (
  16. "encoding/base64"
  17. "fmt"
  18. "io"
  19. "net/http"
  20. "os"
  21. "strings"
  22. "github.com/fatedier/frp/pkg/config"
  23. "github.com/spf13/cobra"
  24. )
  25. func init() {
  26. rootCmd.AddCommand(reloadCmd)
  27. }
  28. var reloadCmd = &cobra.Command{
  29. Use: "reload",
  30. Short: "Hot-Reload frpc configuration",
  31. RunE: func(cmd *cobra.Command, args []string) error {
  32. cfg, _, _, err := config.ParseClientConfig(cfgFile)
  33. if err != nil {
  34. fmt.Println(err)
  35. os.Exit(1)
  36. }
  37. err = reload(cfg)
  38. if err != nil {
  39. fmt.Printf("frpc reload error: %v\n", err)
  40. os.Exit(1)
  41. }
  42. fmt.Printf("reload success\n")
  43. return nil
  44. },
  45. }
  46. func reload(clientCfg config.ClientCommonConf) error {
  47. if clientCfg.AdminPort == 0 {
  48. return fmt.Errorf("admin_port shoud be set if you want to use reload feature")
  49. }
  50. req, err := http.NewRequest("GET", "http://"+
  51. clientCfg.AdminAddr+":"+fmt.Sprintf("%d", clientCfg.AdminPort)+"/api/reload", nil)
  52. if err != nil {
  53. return err
  54. }
  55. authStr := "Basic " + base64.StdEncoding.EncodeToString([]byte(clientCfg.AdminUser+":"+
  56. clientCfg.AdminPwd))
  57. req.Header.Add("Authorization", authStr)
  58. resp, err := http.DefaultClient.Do(req)
  59. if err != nil {
  60. return err
  61. }
  62. defer resp.Body.Close()
  63. if resp.StatusCode == 200 {
  64. return nil
  65. }
  66. body, err := io.ReadAll(resp.Body)
  67. if err != nil {
  68. return err
  69. }
  70. return fmt.Errorf("code [%d], %s", resp.StatusCode, strings.TrimSpace(string(body)))
  71. }