Golang 환경변수 등록 소스

딱히 뭐 없고 이전에 만들었던 “Go 환경변수 등록해주는 프로그램” 이걸 golang으로 작업해봄.
주목적은 golang에서 registry 처리하는거 테스트 하다가 덤으로 만들어진 프로그램


2020년 10월 21일 수정
오늘 알았지만 GOROOT가 필요 없다는거 깨닫고 반영하면서 살짝 정리함.


2020년 7월 26일 수정
윈도우 재설치 하고 golang sdk도 업그레이드 하다가 실수로 폴더 통채로 날려서 환경설정.exe 파일이 날라가는걸 경험하고 살짝 업그레이드 함.

이전처럼 실행 경로를 기준으로 잡지 않고 json 설정파일을 지정해서 내부에 있는 경로를 가져다 등록하는것으로 변경함.


//https://pkg.go.dev/golang.org/x/sys/windows/registry?tab=doc
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"

	"golang.org/x/sys/windows/registry"
)

// Config 는 경로를 저장하는 구조체임.
type Config struct {
	PathSDK       string //SDK			ex) C:\Develop\SDK\Go
	PathWorkspace string //Workspace	ex) C:\Develop\Projects\Go
	PathGit       string //Git			ex) C:\Develop\Tools\Git
}

// NewConfig 는 Config 생성자임.
func NewConfig() *Config {
	d := Config{}
	d.PathSDK = `C:\Develop\SDK\Go`
	d.PathWorkspace = `C:\Develop\Projects\Go`
	d.PathGit = `C:\Develop\Tools\Git`
	return &d
}

// loadConfig 는 설정파일을 읽어들인다.
func loadConfig(conf *Config) {

	fp, err := os.Open("./GoSetEnv.json")
	if err != nil {
		fmt.Println("GoSetEnv.json 파일이 없습니다.")

		jsonBytes, err := json.Marshal(conf)
		if err != nil {
			panic(err)
		}
		fo, err := os.Create("./GoSetEnv.default.json")
		if err != nil {
			panic(err)
		}
		defer fo.Close()

		_, err = fo.Write(jsonBytes)
		if err != nil {
			panic(err)
		}
		fmt.Println("GoSetEnv.default.json 파일을 생성했습니다.")
		fmt.Println()
		fmt.Println("json 파일을 열어서 각 경로를 수정하세요")
		fmt.Println("파일명을 GoSetEnv.json으로 변경후 다시 실행하세요.")

		os.Exit(0)
	}
	defer fp.Close()
	bytes, _ := ioutil.ReadAll(fp)

	err = json.Unmarshal(bytes, &conf)

	fmt.Println("SDK 경로 = " + conf.PathSDK)
	fmt.Println("Workspace 경로 = " + conf.PathWorkspace)
	fmt.Println("Git 경로 = " + conf.PathGit)
	fmt.Println()

}

func main() {

	config := NewConfig()
	loadConfig(config)

	//---------------------------------------------------------------------------------------------
	//레지스트리 오픈
	regKey, err := registry.OpenKey(registry.CURRENT_USER, "Environment", registry.ALL_ACCESS)
	if err != nil {
		fmt.Println("Regkey 오픈실패")
		log.Fatal(err)
	}
	defer regKey.Close()

	//---------------------------------------------------------------------------------------------
	//1. 독립적으로 추가 되는 부분
	err = regKey.SetStringValue("GOPATH", config.PathWorkspace)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("GOPATH 추가 완료 : ", config.PathWorkspace)

	//---------------------------------------------------------------------------------------------
	//2. Path에 추가 되는 부분
	strPath, _, err := regKey.GetStringValue("path")
	if err != nil {
		log.Fatal(err)
	}

	//기존 path 값 끝에 ;가 있는지 확인후 추가
	var pathSize = len(strPath)
	if string(strPath[pathSize-1]) != ";" {
		strPath += `;`
	}

	//sdk\bin 추가
	strPath += (config.PathSDK + `\bin;`)

	//workspace\bin 추가
	strPath += (config.PathWorkspace + `\bin;`)

	//Git\bin 추가
	strPath += (config.PathGit + `\bin`)

	//레지스트리에 등록
	err = regKey.SetStringValue("path", strPath)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(`path 추가 완료`)
	//---------------------------------------------------------------------------------------------
}


Comments

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다