properties.go 2.0 KB

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