properties.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package config
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "regexp"
  6. "strings"
  7. )
  8. //initProperties xxx
  9. func initProperties(serverFolder string) []ServerConfig {
  10. properties := []ServerConfig{}
  11. b, err := ioutil.ReadFile(serverFolder + "/server.properties") // just pass the file name
  12. if err != nil {
  13. fmt.Print(err)
  14. }
  15. str := string(b) // convert content to a 'string'
  16. lines := strings.Split(str, "\n")
  17. for _, line := range lines {
  18. regex := regexp.MustCompile("^(.*)=(.*[^=]*)$")
  19. regexSubmatch := regex.FindStringSubmatch(line)
  20. if len(regexSubmatch) > 0 {
  21. item := ServerConfig{
  22. Key: strings.TrimSpace(regexSubmatch[1]),
  23. Value: strings.TrimSpace(regexSubmatch[2]),
  24. }
  25. properties = append(properties, item)
  26. }
  27. }
  28. return properties
  29. }
  30. //ReadAllProperties is exported function
  31. func (mch *Handler) ReadAllProperties() []ServerConfig {
  32. return mch.properties
  33. }
  34. //ChangeProperties is exported function
  35. func (mch *Handler) ChangeProperties(inputKey string, inputValue string) bool {
  36. for i, item := range mch.properties {
  37. if strings.ToLower(inputKey) == strings.ToLower(item.Key) {
  38. mch.properties[i].Value = inputValue
  39. }
  40. }
  41. return true
  42. }
  43. //SaveProperties is exported function
  44. func (mch *Handler) SaveProperties() bool {
  45. TXT := "#Minecraft server properties"
  46. for _, line := range mch.properties {
  47. TXT += line.Key + "=" + line.Value + "\n"
  48. }
  49. err := ioutil.WriteFile(mch.serverFolder+"/server.properties", []byte(TXT), 0777)
  50. if err != nil {
  51. fmt.Println(err)
  52. }
  53. return true
  54. }
  55. //There is no delete or add function because it is not necessary :)