hostedit

package module
v0.0.0-...-84055a7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 10, 2024 License: GPL-3.0 Imports: 6 Imported by: 0

README

go-hosts-edit-library

host file edit library by Golang. Golang的hosts文件编辑库。

Quick start

package main

import hostsedit "github.com/Deng-Xian-Sheng/go-hosts-edit-library"

func main() {
	// Create a file to ./hosts , as the following:
	/*
	   127.0.0.1 localhost
	   ::1 localhost
	   # Comment line
	   1.1.1.1 google.com
	   2.2.2.2 baidu.com
	*/

	// init
	// 初始化
	hostEdit,err :=  hostsedit.New("./hosts",false)
	if err != nil {
		panic(err)
	}

	// get ip by host
	// 通过主机获取ip
	v,ok := hostEdit.Get("google.com")
	if ok {
		println(v)
	}

	// edit ip by host, If the host is not in the hosts file, it will create a new one
	// 通过主机编辑ip,如果主机不在hosts文件中,它会新建一条
	err = hostEdit.Edit("google.com","3.3.3.3")
	if err != nil {
		panic(err)
	}

	ok = hostEdit.Exists("baidu.com")
	if ok {
		println("baidu.com exists hosts file")
	}else{
		println("baidu.com not exists hosts file")
	}

    // not exists no error
	err = hostEdit.Delete("baidu.com")
	if err != nil {
		panic(err)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type HostsEdit

type HostsEdit struct {
	Lines    []*Line
	FilePath string
}

HostsEdit represents the entire hosts file and provides methods to manipulate it.

func New

func New(filePath string, isParse bool) (*HostsEdit, error)

New loads the hosts file from the specified path and returns a HostsEdit instance. isParse 是否进行严格的语法分析,如果启用则不容忍注释行以外的重复的主机、不规范的主机的条目,遇到此类会报错。但操作系统在这种情况下往往不会报错,与操作系统的行为不符。

func (*HostsEdit) Delete

func (h *HostsEdit) Delete(host string) (err error)

Delete removes the specified host from the hosts file. not exists no error

func (*HostsEdit) Edit

func (h *HostsEdit) Edit(host, ip string) (err error)

Edit adds or updates the specified host with the given IP address.

func (*HostsEdit) Exists

func (h *HostsEdit) Exists(host string) bool

Exists checks if the specified host exists in the hosts file.

func (*HostsEdit) Get

func (h *HostsEdit) Get(host string) (string, bool)

Get returns the IP address of the specified host.

type Line

type Line struct {
	IsComment           bool
	UndefinedRowsRawStr string
	IP                  string
	Host                map[string]struct{} // 注意,会使多个主机之间无序,但是这貌似是不可避免的。
	IsDelete            bool
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL