Simple hosts file management in Go (golang).
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

51 lines
902 B

  1. package goodhosts
  2. import (
  3. "fmt"
  4. "net"
  5. "strings"
  6. )
  7. // HostsLine Represents a single line in the hosts file.
  8. type HostsLine struct {
  9. IP string
  10. Hosts []string
  11. Comment string
  12. Raw string
  13. Err error
  14. }
  15. // NewHostsLine Return a new instance of ```HostsLine```.
  16. func NewHostsLine(raw string) HostsLine {
  17. fields := strings.Fields(raw)
  18. if len(fields) == 0 {
  19. return HostsLine{Raw: raw}
  20. }
  21. output := HostsLine{Raw: raw}
  22. if !IsComment(output.Raw) {
  23. rawIP := fields[0]
  24. if net.ParseIP(rawIP) == nil {
  25. output.Err = fmt.Errorf("Bad hosts line: %q", raw)
  26. }
  27. output.IP = rawIP
  28. var outputFields []string
  29. for i, field := range fields {
  30. if IsComment(field) {
  31. output.Comment = strings.Join(fields[i:], " ")
  32. output.Comment = output.Comment[1:]
  33. break
  34. }
  35. outputFields = append(outputFields, field)
  36. }
  37. output.Hosts = outputFields[1:]
  38. }
  39. return output
  40. }