windows使用go语言调用https://raw.hellogithub.com/hosts更新GitHub相关hosts

208 阅读1分钟

windows使用go语言调用https://raw.hellogithub.com/hosts更新GitHub相关hosts

GitHub520: 本项目无需安装任何程序,通过修改本地 hosts 文件,试图解决: GitHub 访问速度慢的问题 GitHub 项目中的图片显示不出的问题 花 5 分钟时间,让你"爱"上 GitHub。 (gitee.com)

需要管理员权限执行!

main.go

package main

import (
	"bufio"
	"fmt"
	"io"
	"net/http"
	"os"
	"os/exec"
	"strings"
)

func main() {
	writeHosts()
	exec.Command("cmd", "/C", "ipconfig /flushdns")
}

func getHosts() string {
	res, _ := http.Get("https://raw.hellogithub.com/hosts")
	bodyB, _ := io.ReadAll(res.Body)
	return string(bodyB)
}

func writeHosts() {
	fi, _ := os.Open("C:/Windows/System32/drivers/etc/hosts")
	fr := bufio.NewReader(fi)
	doWrite := true
	arr := make([]string, 0, 64)
	for {
		line, err := fr.ReadString('\n')
		if err == io.EOF {
			break
		}
		line = strings.TrimSpace(line)
		if strings.Compare("# GitHub520 Host Start", line) == 0 {
			doWrite = false
		}
		if doWrite {
			arr = append(arr, line)
		}
		if strings.Compare("# GitHub520 Host End", line) == 0 {
			doWrite = true
		}
	}
	newHosts := getHosts()
	f, err := os.OpenFile("C:/Windows/System32/drivers/etc/hosts", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
	if err != nil {
		fmt.Println("write error!", err)
	}
	defer f.Close()
	rn := []byte{'\r', '\n'}
	for _, d := range arr {
		f.WriteString(d)
		if len(d) >= 1 && !strings.HasSuffix(d, "\n") {
			f.Write(rn)
		}
	}
	f.Write(rn)
	f.WriteString(newHosts)
	f.Write(rn)
	f.Sync()
}

使用c#更简单一点,可以更便捷创建app.manifest以直接启动获取管理员权限

Program.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

string path = System.Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\drivers\\etc\\hosts";

List<string> oldHosts() {
    string[] hosts = File.ReadAllLines(path);
    List<string> list = new();
    bool doWrite = true;
    foreach (string host in hosts) {
        if (host.Contains("# GitHub520 Host Start")) doWrite = false;
        if (doWrite) list.Add(host);
        if (host.Contains("# GitHub520 Host End")) doWrite = true;
    }
    int sCount = 0;
    for(int i = list.Count() - 1; i >= 0; --i) {
        var s = list[i];
        if (String.IsNullOrEmpty(s)) {
            if (i == list.Count() - 1) sCount = 1;
            else if (sCount >= 1) ++sCount;
        } else break;
    }
    if(sCount > 2) list.RemoveRange(list.Count() - sCount, sCount - 1);
    return list;
}

void rmHosts() {
    File.WriteAllLines(path, oldHosts().ToArray());
    Console.WriteLine("移除获取到的 GitHub host");
}

void setHosts() {
    var hostsList = githubHost();
    Console.WriteLine("获取到 GitHub host");
    Console.WriteLine(hostsList);
    var list = oldHosts();
    list.Add(hostsList);
    File.WriteAllLines(path, list.ToArray());
    Console.WriteLine("完成 GitHub host 写入");
}

string githubHost() {
    HttpClient httpClient = new() {
        BaseAddress = new Uri("https://raw.hellogithub.com/hosts")
    };
    var resp = httpClient.GetStringAsync("");
    return resp.GetAwaiter().GetResult();
}

if (args.Length >= 1 && "-rm".Equals(args[0])) rmHosts();
else setHosts();

app.manifest

<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>