properties.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. //ReadProperties is exported function
  44. func (mch *Handler) ReadProperties(inputKey string) string {
  45. for i, item := range mch.properties {
  46. if strings.ToLower(inputKey) == strings.ToLower(item.Key) {
  47. return mch.properties[i].Value
  48. }
  49. }
  50. return ""
  51. }
  52. //SaveProperties is exported function
  53. func (mch *Handler) SaveProperties() bool {
  54. TXT := "#Minecraft server properties"
  55. for _, line := range mch.properties {
  56. TXT += line.Key + "=" + line.Value + "\n"
  57. }
  58. err := ioutil.WriteFile(mch.serverFolder+"/server.properties", []byte(TXT), 0777)
  59. if err != nil {
  60. fmt.Println(err)
  61. }
  62. return true
  63. }
  64. //There is no delete or add function because it is not necessary :)