반응형

오늘은 실행파일 아이콘이미지 하나 만들다가 배경을 선택하고 delete를 눌러도 하얀 배경이 지워지질 않았습니다. 그래서 알아본 GIMP로 투명한 배경을 만드는 방법!!


1.우선 이미지를 하나 가져오겠습니다.

 

 


2. 배경을 투명하게 만들 곳을 선택하고 삭제를 합니다. 역시 아직 하얀색으로 보입니다. ( 퍼지선택영역도구로 선택후 delete 아니면 우클릭 메뉴에서 삭제 ) 이건 배경색이 흰색으로 설정되어있기 때문입니다.

 

 


 

 




3. 투명으로 만들기 위해서는 "레이어" 창에서 현재 레이어를 우클릭해 "알파 채널 추가"를 합니다.

 

 


5. 선택된 곳을 다시 삭제! 이제 투명배경이 된것을 볼 수 있습니다.

 

 


6. 기존 파일에 덮어쓰던 다른이름으로 내보내던 하시면 되겠습니다.

 

 


- 끝 - 

반응형
반응형

순서가 뒤바뀐 감이 없진 않지만... 저도 배우는 입장이라, 뒤늦게 알게된 것을 바로바로 포스팅합니다.

오늘은 Go언어 windows환경에 제대로 설치하기입니다. 순서는

1. 설치

2. 환경변수 설정

3. Hello World 출력

이 되겠습니다.

 

1. GO 설치

Go 공식 웹사이트인 http://golang.org/dl 에서 본인의 OS에 맞는 Go를 다운로드하여 설치합니다. Go는 Windows, Linux, Mac OS X 에서 사용할 수 있습니다.

 

 

Windows에 Go를 설치하기 위해서는 MSI 파일을 다운받아 실행하면 됩니다.

Go는 디폴트로 C:\go 폴더에 설치되며, MSI가 C:\go\bin을 PATH 환경변수가 자동으로 추가됩니다.

 

2. 환경변수 설정

Go는 2개의 중요한 환경변수(GOROOT와 GOPATH)를 사용합니다..
 

GOROOT:

 Go가 설치된 디렉토리(윈도우즈의 경우 디폴트로 C:\Go)를 가리키며, Go 실행파일은 GOROOT/bin 폴더에, Go 표준 패키지들은 GOROOT/pkg 폴더에 존재합니다. 윈도우즈에 GO 설치시 시스템 환경변수로 자동으로 설정됩니다.

 

 GOPATH:

 Go는 표준 패키지 이외의 3rd Party 패키지나 사용자 정의 패키지들을 이 GOPATH 에서 찾습니다. 복수 개의 경로를 지정한 경우, 3rd Party 패키지는 처음 경로에 설치됩니다. 그런데 최초 설치시 GOPATH가 C:\C:\Users\USER\go로 지정됩니다. 따라서 다른 폴더를 적용하고 싶을 경우에는 적당한 폴더로 변경해주는 게 좋을 것 같습니다.

 

GOROOT나 GOPATH나 모두 최초 설치시에는 사용자 변수로 등록되므로, 저는 삭제하고 다시 시스템 변수로 등록해주었습니다. 그리고 GOPATH는 3rd party 패키지 설치를 위한 폴더, 직접 작업할 파일 폴더, 이렇게 두 폴더를 각각 지정해 두었습니다.

 

 

 

3. Hello World 출력

LiteIDE로 작업을 했습니다. 폴더 하나를 생성하고, hello.go파일을 만들면 자동으로 아래와 같이 디폴트로 코드가 생성됩니다. 여기서 BR을 눌러줘도 되구요... (main함수가 한 폴더에 두개이상 존재하면 에러가 나기 때문에, 별도의 폴더를 생성하는 것이 필요합니다.)

 

 

커맨드 창에서 실행해도 잘 출력되는 것을 확인할 수 있습니다.

 

 

이상으로 Go언어 설치/환경변수 설정/Hello world 출력하는 방법에 대해 간단히 알아보았습니다.

 

-끝-

반응형
반응형

 

이번엔 gtk toolkit 전용 GUI Designer인 Glade를 이용하여 Go언어에서 활용해보도록 하겠습니다.

 

우선 Glade를 설치해야 합니다. linux에서는 비교적 쉽게 찾아서 설치 가능한데요.. 윈도우에서는 조금 설치가 쉽지 않습니다. Mingw를 설치하고 아래의 명령으로 설치를 진행해줍니다.

pacman -S mingw-w64-x86_64-glade

빠른 실행을 위해서는 sourceforge 사이트에서 예전버전을 다운받는 것도 괜찮아보입니다.

 

 

다음으로는 Glade에서 UI를 적당히 디자인 해줍니다. (glade예제파일)

생각해보니...그냥 적당히는 안될 것 같네요.

 

 

1. 최상위 - > GtkWindow 를 선택해주세요. 그리고 아이디를 main_window,  사이즈를 440, 250 으로 설정합니다.

2. 컨테이너-> GtkHeaderBar를 선택해주세요. 아이디를 headerbar, 간격 7, 항목 3으로 설정해주세요

3. 컨트롤->GtkButton 3개를 생성해서 아이디를 TestBtn, HelloBtn, exitBtn으로 해주세요. 그리고 그에 맞게 레이블도 수정해 줍니다.

이렇게 구성하면 glade2.glade 로 저장합니다. 물론 아무 이름이나 상관 없습니다만, 그럴 경우 아래 소스코드의 파일명 부분을 적당히 수정해주세요. 이제 아래의 소스코드를 수행해봅니다.

// gotk_glade.go
package main

import (
	"errors"
	"fmt"
	"log"
	"os"
	"reflect"

	"github.com/gotk3/gotk3/glib"
	"github.com/gotk3/gotk3/gtk"
)

var headerBar *gtk.HeaderBar

func main() {
	// Create a new application.
	application, err := gtk.ApplicationNew("new.test", glib.APPLICATION_FLAGS_NONE)
	errorCheck(err)

	// Connect function to application startup event, this is not required.
	application.Connect("startup", func() {
		log.Println("application startup")
	})

	// Connect function to application activate event
	application.Connect("activate", func() {
		log.Println("application activate")

		// Get the GtkBuilder UI definition in the glade file.
		builder, err := gtk.BuilderNewFromFile("glade2.glade")
		errorCheck(err)

		// Map the handlers to callback functions, and connect the signals
		// to the Builder.
		signals := map[string]interface{}{
			"on_main_window_destroy": onMainWindowDestroy,
			"on_HelloBtn_clicked":    clickedTestButton,
		}
		builder.ConnectSignals(signals)

		// Get the object with the id of "main_window".
		obj, err := builder.GetObject("main_window")
		fmt.Println(reflect.TypeOf(obj))
		errorCheck(err)

		// Verify that the object is a pointer to a gtk.ApplicationWindow.
		win, err := isWindow(obj)
		fmt.Println(reflect.TypeOf(win))
		errorCheck(err)

		headerBar, err := builder.GetObject("headerbar")
		errorCheck(err)
		fmt.Println(reflect.TypeOf(headerBar))
		//headerBar.SetTitle("sss")

		// Show the Window and all of its components.
		win.Show()
		application.AddWindow(win)
	})

	// Connect function to application shutdown event, this is not required.
	application.Connect("shutdown", func() {
		log.Println("application shutdown")
	})

	// Launch the application
	os.Exit(application.Run(os.Args))
}

func isWindow(obj glib.IObject) (*gtk.Window, error) {
	// Make type assertion (as per gtk.go).
	if win, ok := obj.(*gtk.Window); ok {
		return win, nil
	}
	return nil, errors.New("not a *gtk.Window")
}

func errorCheck(e error) {
	if e != nil {
		// panic for any errors.
		log.Panic(e)
	}
}

// onMainWindowDestory is the callback that is linked to the
// on_main_window_destroy handler. It is not required to map this,
// and is here to simply demo how to hook-up custom callbacks.
func onMainWindowDestroy() {
	log.Println("onMainWindowDestroy")
}

func clickedTestButton() {
	fmt.Println("Testclick")
	//headerBar.SetTitle("New Title!!")
}


모두들 성공하시길 빌겠습니다.
그럼 이만~~

 

반응형
반응형

Go언어로 Oracle 연결하기 위한 드라이버가 몇가지가 있는데, 그 중 Setting이 간단하고 실행 가능했던 드라이버가 godror 였습니다. 아래는 참조한 사이트이구요..

https://blogs.oracle.com/developers/how-to-connect-a-go-program-to-oracle-database-using-goracle

How to Connect a Go Program to Oracle Database using godror

Note: This blog post was updated from the original to reflect the new name for the Go Driver for Oracle Database: godror, ormerly known as goracle. Oracle has offered Go programming language RPMs on Oracle Linux yum server, for a while now. In this post, I

blogs.oracle.com

(ps) 아래와 같은 드라이버도 있는데, 

gopkg.in/rana/ora.v4

github.com/mattn/go-oci8

oci8.pc라는 파일을 세팅해야하는데 잘 안되서 중간에 설치하다가 계속 실패했습니다.

 

godror를 기준으로 설명하자면....

 

1. 우선 Oracle Instant Client 를 설치해야 합니다. 이건 다른 드라이버들을 설치한다고 해도 공통적인 사항입니다.

2. godror을 아래 명령어로 설치를 합니다.

go get github.com/godror/godror

3. 아래의 소스를 작성해서 테스트해 봅니다.

package main

import (
	"database/sql"
	"fmt"

	_ "github.com/godror/godror"
)

func main() {

	db, err := sql.Open("godror", "username/password@service_name:port/SID")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer db.Close()

	rows, err := db.Query("select EMP_#1 from TEMP where NAME='홍길동'")
	if err != nil {
		fmt.Println("Error running query")
		fmt.Println(err)
		return
	}
	defer rows.Close()

	var emp string			// DB에서 받을 데이터를 저장할 변수 선언

	for rows.Next() {

		rows.Scan(&emp)		// DB에서 받은 데이터 할당
	}
	fmt.Printf("The date is: %s\n", emp)
}

 

별다른 설정 없이도 설치만으로 DB 접속할 수 있는 환경이 구성됩니다.

이상 Go언어로 Oracle DB에 접속하는 방법 끝.~~

반응형
반응형

 

사내에서 사용할 간단한 GUI프로그램 개발 환경을 구상 중입니다. 배포도 해야해서 VM위에서 돌아가는 Java는 좀 꺼림직하고... 다른 언어로 쓸 수 있는 GUI Toolkit을 찾아보다가 결국 QT/GTK/WxWidgets 로 가야할 것 같은데요. 배포가 어렵다는 C/C++로 가는 것 보다는 요즘 언어인 Go언어로, 그리고 바인딩이 잘 되어있는 GTK로 가보려고 합니다. Go언어 바인딩은 Gotk3가 있습니다. 이번 포스트에서는 Gotk3설치 및 예제 프로그래밍까지 수행해 보겠습니다.

 

우선 사전 준비해야 하는 작업이 좀 있습니다. 생각보다....(이거 하면서 그냥 Swing써야겠다고 생각하는 중....ㅠㅠ)

1. git 설치

2. MinGW-w64설치(MSYS2설치)

3. GTK 및 dependencies 설치

4. MinGW 환경변수 추가

5. Gotk3 설치

6. 예제 실행

 

1. GIT 설치

요기 사이트로 가서 Git을 설치합니다. 요즘은 Git을 알아야 한다는데,, 아직 제가 잘 몰라서,,

나중에 공부해서 올리는 것으로 하고, 우선 설치하겠습니다.

 

 

 

 

 

 

2. MinGW-w64설치(MSYS2설치)

요기 사이트에서 msys2-x86_64-xxxxxxx.exe파일을 다운받아 설치해 줍니다. 이걸 설치하면 리눅스에서 사용하던 터미널이 생깁니다. 그럼 리눅스 명령어로 GTK를 설치할 준비가 됩니다.

 

 

 

 

 

 

설치하고 나면 저런 터미널이 뜹니다.

 

 

 

MinGW(MSYS2)를 실행한 모습

 

 

 

3. Dependencies 설치

방금 설치한 MSYS2 터미널을 찾아 실행해 보겠습니다.

 

 

 

 

 

 

그리고 아래 명령을 차례로 수행해주세요.

  1) pacman --noconfirm --needed -Sy bash pacman pacman-mirrors

  2) pacman --noconfirm -Su

  3) pacman --noconfirm -S mingw-w64-x86_64-gcc mingw64/mingw-w64-x86_64-pkg-config mingw-w64-x86_64-gtk3

 

 

 

 

 

 

마지막 명령에서 에러가 마구 발생을 하네요...ㅠㅠ.

구글링 하다가...터미널 창 새로 열고 실행했더니 잘 되는 듯 합니다. 그러다가 또 에러 반복..이건 뭔지....ㅠㅠ

결국 패키지 별로 나누어 설치하고 나서야 성공합니다.

그리고 추가로

bash -c "sed -i -e 's/-Wl,-luuid/-luuid/g' C:/msys64/mingw64/lib/pkgconfig/gdk-3.0.pc"

를 마지막에 한번 실행해 줘야 나중에 컴파일 할 때 에러가 없습니다. 버그픽스 명령어 같습니다.

 

4. MinGW 환경변수 추가

- C:\msys64\mingw64\bin

- C:\msys64\usr\bin

요 두 폴더를 Path에 추가해줍니다.

 

 

 

 

 

 

5. Gotk3 설치

이제 진짜 Gotk3가 설치되는지 보겠습니다. 이번엔 Git 터미널에서 아래 명령어를 수행합니다.

go get github.com/gotk3/gotk3/gtk

 

 

 

 

 

 

뭔가 에러가 조금 있었지만, Fail은 아닌 것 같습니다.

한번 아래 코드로 실행이 되는지 보겠습니다.

 

6. 예제 실행

아래 소스를 입력하고 Build&Run을 수행합니다.

Golang이 원래 컴파일이 엄청 빠른 언어인데, 최초 컴파일 때는 시간이 많이 걸립니다. 낼 출근이 심히 걱정됩니다...

4시간 자야되네...ㅠㅠ이게 머라고..

package main

import (
	"log"

	"github.com/gotk3/gotk3/gtk"
)

func main() {
	// Initialize GTK without parsing any command line arguments.
	gtk.Init(nil)

	// Create a new toplevel window, set its title, and connect it to the
	// "destroy" signal to exit the GTK main loop when it is destroyed.
	win, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
	if err != nil {
		log.Fatal("Unable to create window:", err)
	}
	win.SetTitle("Simple Example")
	win.Connect("destroy", func() {
		gtk.MainQuit()
	})

	// Create a new label widget to show in the window.
	l, err := gtk.LabelNew("Hello, gotk3!")
	if err != nil {
		log.Fatal("Unable to create label:", err)
	}

	// Add the label to the window.
	win.Add(l)

	// Set the default window size.
	win.SetDefaultSize(800, 600)

	// Recursively show all widgets contained in this window.
	win.ShowAll()

	// Begin executing the GTK main loop.  This blocks until
	// gtk.MainQuit() is run.
	gtk.Main()
}

 

 

 

 

 

 

야호~~성공~~!!

이제 자러갑시다..^^;;;;;

 

Glade와 연동하는 건 다음기회에...

반응형
반응형

Go 언어로 간단한 GUI 구현을 위한 라이브러리로 andlabs/ui라는게 있습니다. 나중에 포스팅할 Glade 같은 GUI designer를 사용하여 구현할 정도가 아니라 간단한 GUI수준을 위해서는 괜찮은 방법인 것 같습니다.

 

우선 Linux에서 설치는

go get github.com/andlabs/ui

로 터미널에 입력하여 설치해줍니다.

Windows환경에서는 MinGW를 실행해서 설치해야 합니다.

 

그리고 아래의 예제코드를 입력하고 실행하면...

package main

import (
	"github.com/andlabs/ui"
	_ "github.com/andlabs/ui/winmanifest"
)

func main() {
	err := ui.Main(func() {
		input := ui.NewEntry()
		button := ui.NewButton("Greet")
		greeting := ui.NewLabel("")
		box := ui.NewVerticalBox()
		box.Append(ui.NewLabel("Enter your name:"), false)
		box.Append(input, false)
		box.Append(button, false)
		box.Append(greeting, false)
		window := ui.NewWindow("Hello", 200, 100, false)
		window.SetMargined(true)
		window.SetChild(box)
		button.OnClicked(func(*ui.Button) {
			greeting.SetText("Hello, " + input.Text() + "!")
		})
		window.OnClosing(func(*ui.Window) bool {
			ui.Quit()
			return true
		})
		window.Show()
	})
	if err != nil {
		panic(err)
	}
}

 

 

 

Go 언어를 이용하여 정말 간단한 UI를 한번 구현해 보았습니다.

 

- 끝 - 

반응형

'Programming > Golang' 카테고리의 다른 글

Go언어 oracle 연결  (2) 2020.03.26
Gotk3를 이용한 go언어 GUI 개발 예제  (0) 2020.03.16
Go언어 초간단 async 예제  (0) 2020.03.16
Go언어-파일찾기 프로그램 예제  (0) 2020.03.16
Go언어 - liteIDE설치 및 실행  (2) 2020.03.16
반응형

Go언어의 장점 중 하나로 비동기 함수실행을 매우 쉽게 구현한다는 점입니다.

비동기 프로그래밍을 직접 해본적이 없어서 잘은 모르지만, 아래 예제를 보니 정말 쉬운 것 같습니다.

package main

import (
	"fmt"
	"time"
)

func say(s string) {
	for i := 0; i < 10; i++ {
		fmt.Println(s, "***", i)
	}
}

func main() {
	// 함수를 동기적으로 실행
	say("Sync")

	// 함수를 비동기적으로 실행
	go say("Async1")
	go say("Async2")
	go say("Async3")

	// 3초 대기
	time.Sleep(time.Second * 3)
}

 

결과

C:/Go/bin/go.exe build [D:/5.System_dev/7_GO/async]
Success: process exited with code 0.
D:/5.System_dev/7_GO/async/async.exe  [D:/5.System_dev/7_GO/async]
Sync *** 0
Sync *** 1
Sync *** 2
Sync *** 3
Sync *** 4
Sync *** 5
Sync *** 6
Sync *** 7
Sync *** 8
Sync *** 9
Async2 *** 0
Async1 *** 0
Async1 *** 1
Async1 *** 2
Async1 *** 3
Async1 *** 4
Async1 *** 5
Async1 *** 6
Async1 *** 7
Async1 *** 8
Async1 *** 9
Async2 *** 1
Async2 *** 2
Async2 *** 3
Async2 *** 4
Async2 *** 5
Async2 *** 6
Async2 *** 7
Async2 *** 8
Async2 *** 9
Async3 *** 0
Async3 *** 1
Async3 *** 2
Async3 *** 3
Async3 *** 4
Async3 *** 5
Async3 *** 6
Async3 *** 7
Async3 *** 8
Async3 *** 9
Success: process exited with code 0.

-끝-

반응형
반응형

Go 언어로 작성한 파일찾기 프로그램 예제입니다. 검색하고자 하는 Directory와 파일명을 입력하면 찾는 프로그램입니다. 사용 방법은

filecheck.exe <검색Dir> <대상file>

과 같이 사용하면 되며, 아래 예시와 같이 사용하면 됩니다.

 

 

 

소스코드는 아래와 같습니다.

package main

import (
	"fmt"
	"os"
	"path/filepath"
)

var (
	targetFolder string
	targetFile   string
	searchResult []string
)

func findFile(path string, fileInfo os.FileInfo, err error) error {
	if err != nil {
		fmt.Println(err)
		return nil
	}

	absolute, err := filepath.Abs(path)
	if err != nil {
		fmt.Println(err)
		return nil
	}

	if fileInfo.IsDir() {
		fmt.Println("Searching directory ...", absolute)
		testDir, err := os.Open(absolute)

		if err != nil {
			if os.IsPermission(err) {
				fmt.Println("No permission to scan ...", absolute)
				fmt.Println(err)
			}
		}
		testDir.Close()
		return nil
	} else {
		matched, err := filepath.Match(targetFile, fileInfo.Name())
		//matched, err := filepath.Glob(targetFile)
		if err != nil {
			fmt.Println(err)
		}
		if matched {
			add := "Found : " + absolute
			searchResult = append(searchResult, add)
		}
	}
	return nil
}

func main() {
	if len(os.Args) != 3 {
		fmt.Printf("USAGE : %s <target_directory> <target_file> \n", os.Args[0])
		os.Exit(0)
	}

	targetFolder = os.Args[1]
	targetFile = os.Args[2]

	fmt.Println("Searching for [", targetFolder, "]")

	testFile, err := os.Open(targetFolder)
	if err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
	defer testFile.Close()

	testFileInfo, _ := testFile.Stat()
	if !testFileInfo.IsDir() {
		fmt.Println(targetFolder, " is not a directory!")
		os.Exit(-1)
	}

	err = filepath.Walk(targetFolder, findFile)

	if err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}

	fmt.Println("\n\nFound ", len(searchResult), " hits!")
	fmt.Println("@@@@@@@@@@@@@@@@@@@@@@")

	for _, v := range searchResult {
		fmt.Println(v)
	}
}

 

- 끝 -

반응형

+ Recent posts