구글에서 개발한 프로그래밍언어
오픈소스
6살 ( 2015.10.10 )
정적 타입언어
컴파일과 인터프리터 기능을 모두 지원
GC ( 가비지 컬랙션 )
Go Program Language is ...
google 만 믿고 가는 겁니다.
없어진 것도 많긴 하지만......
6년동안 잘 버텼으니..
GOOD
go 언어의 능력이면1000 클라이언트 ( 10000클라이언트 에서도 속도 저하는
10% 이하) 에서 150000 패킷 / 초 정도를 처리 할 수 있습니다.
파이썬에선 정말로 최후까지 쥐어 짜야 60000넘기는 것도 힘들었던것에 비하면
깨끗한 구조를 유지하면서도 2.5배 이상의 성능을 낼수 있는 것이지요.
출처 : http://kasw.blogspot.kr/2015/02/goguelike.html_
언어가 간단하다.
지원하는 패키지가 많다.
동시성 ( Concurrency ) 구현이 쉽다.
node 보단 빠르다.
6.
출처 : 가장빨리 만나는 Go 언어 ( http://pyrasis.com/book/GoForTheReallyImpatient/Unit01/05 )
v1.5 부터 default 스레드 개수가
cpu 코어개수로 변경되었습니다.
Multi thread & Goroutine
Coding
package main
import (
"fmt"
)
funcGetWelcomeString() string {
return "Hello World"
}
func main() {
fmt.Println(GetWelcomeString())
}
GetWelcomString 함수는
Test 코드를 위해서 별도로 분리했습니다.
10.
Test code
package main
import(
. "gopkg.in/check.v1"
"testing"
)
func Test(t *testing.T) { TestingT(t) }
type DemoTest struct{}
var _ = Suite(&DemoTest{})
func (s *DemoTest) TestWelcomeStringTest(c *C) {
c.Assert(GetWelcomeString(), Equals, "Hello World!")
}
_test.go 파일을 테스트하는데 사용하고,
Test하려는 함수이름은 Test 로 시작해야 합니다.
함수 앞에 go라는 키워드만 붙이면
비동기 함수가 됩니다.
클로저 ( closure )를 지원하지만,
Thread-Safe 는 아닙니다.
Goroutine
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go say("world")
say("hello")
}
go playground
14.
채널은 스레드 세이프한메시지 큐 같은거라고 보시면 됩니다.
input 함수에서는 0부터 19까지 전달하고
ouput 함수에서는 화면에 출력함 하는 함수 입니다.
func main() {
ch := make(chan int)
q := make(chan int)
go input(ch, q)
go output(ch, q)
time.Sleep(500)
}
Channel (1)
15.
c 는 input함수로 부터 받아오는 채널이고
q 는 loop를 빠져나가기 위해 사용했습니다.
func input(c chan int, q chan int) {
for i := 0; i < 20; i++ {
c <- i
}
q <- 0
}
func output(c chan int, q chan int) {
for {
select {
case i := <-c:
fmt.Printf("%d,", i)
case <-q:
break
}
}
}
Channel (2)
16.
package main
import (
"fmt"
"net/http"
)
funcMainPage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Request ", r.Method)
}
func main() {
http.HandleFunc("/", MainPage)
http.ListenAndServe("0.0.0.0:8080", nil)
}
간단합니다.
Simple is the BEST
Simple Web Page
자매품 : 기본 패키지보다 더 빠른
valyala/fasthttp
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
)
func MainPage(whttp.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
pageid := vars["id"]
fmt.Fprintln(w, "Request ", r.Method, pageid)
}
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/{id}", MainPage)
http.ListenAndServe("0.0.0.0:8080", router)
}
Gorilla 의 Router 를 이용한 REST 구현
URI 에서 변수부분을 처리하기 위해
고릴라에서 라우터만 가져다 씁니다.
19.
>protoc.exe --go_out=./base.proto 명령으로base.pb.go 파일이 생성됩니다.
Protobuf-go (1)
import (
"./base"
"github.com/golang/protobuf/proto"
"log"
)
protobuf 는 google 출신인데도 불편한점이 있습니다.
proto 파일이 여러개사용할 때 proto 의 package 가 많이 있으면
go 에서는 폴더이름으로 pakage 를 사용하기때문입니다.
package base;
message CONNECT_REQ
{
optional string UserId = 2;
optional string UserPwd = 3;
}
20.
Protobuf-go (2)
func main(){
send := &base.CONNECT_REQ{
UserId: proto.String("test1"),
UserPwd: proto.String("passwd"),
}
data, _ := proto.Marshal(send)
log.Println("Marchal length = ", len(data))
log.Println("Marchal data = ", data)
recv := &base.CONNECT_REQ{}
proto.Unmarshal(data, recv)
log.Println("Unmarchal = ", recv)
}
message 별로 struct 가 생성되기 때문에 객체를 생성해서
byte data를 Marshal, Unmarshal 하면 됩니다.
BAD
공식 IDE 가없음
vim + vim-go
IntelliJ
lite-ide ( https://code.google.com/p/liteide/ )
sublime + sublime-go
visual studio code
emacs ....
윈도우에서 사용할 만한 Debuger 가 아직 없음
생각보다 에러처리 코드가 많이 들어감
패키지에 대한 버전관리가 어렵다.
그나마 lite-ide 가 디버깅이 되는데
고루틴 디버깅이 아직 잘 안되요.
#6 2011년 6월 17일에는 Go와 node.js를 성능 비교했을 때는 Go가 node.js에 비해 45% 정도 느렸지만 2015년 1월 13일 현재는 3배 정도 빠르게 나옴
현재는 버전은 Go는 1.4, node.js는 0.10.35 (2015년 1월)
2015년 11월 node 는 io.js 와 다시 합쳐서 5.1.0 이고, go 는 1.5.1 ( stable 기준 )
#7 기존에는 default 가 1이었지만
v1.5 부터는 n 이 cpu 에서 가능한 개수 ( core 개수 ) 로 변경되었다.
runtime.NumCPU() 로 확인 가능
#8 https://play.golang.org/p/F8Ev-6husG ( go play ground 를 통해서 시연 )
#9 bin 폴더는 go install 을 하게 되면 bin 폴더에 exe 가 생김
pkg library 가 저장됨
src git 으로 부터 받은 src 가 저장됨