본문 바로가기

golang4

[#golang] 스페이스(white space) 여러 개를 1개로 바꾸기 텍스트를 다듬다 보면 스페이스, 띄워쓰기(white space) 여러개를 1개로 바꾸고 싶을 때가 있다. 이 경우, 정규식으로 간단하게 해결할 수 있다. package main import ( "regexp" ) // RemoveMultiSpaces : 스페이스 삭제 func RemoveMultiSpaces(str string) string { reLeadcloseWhtsp := regexp.MustCompile(`^[\s\p{Zs}]+|[\s\p{Zs}]+$`) reInsideWhtsp := regexp.MustCompile(`[\s\p{Zs}]{2,}`) result := reLeadcloseWhtsp.ReplaceAllString(str, "") result = reInsideWhtsp.Replac.. 2020. 3. 30.
[#golang] html 태그 제거(strip tags) golang으로 html 페이지를 크롤링하다보면 가끔 태그를 제거하고 텍스트만 받고 싶은 경우가 있다. 이럴때는 package main import ( "fmt" "github.com/grokify/html-strip-tags-go" ) func main() { text := "Hello World!this is in div element." stripped := strip.StripTags(text) fmt.Println(text) fmt.Println(stripped) } 를 사용하면 간단하게 해결할 수 있다. 2020. 3. 30.
[#golang] 소스코드에서 커맨드 실행하기 golang 안에서 git clone 또는 git pull을 하는 등 직접 커맨드를 실행해야 하는 경우가 많다. 이번 포스팅에선 golang 안에서 직접 커맨드를 실행하는 방법에 대해서 알아보자 예를들면 워킹 디렉토리(working directory) /test/workspace 안에서 ls -a 를 실행하는 커맨드를 입력한다고 하면 아래와 같은 방식으로 사용할 수 있다. import ( "os/exec" ) cmd := exec.Command("ls", "-a") cmd.Dir = "/test/workspace" output, err := cmd.Output() if err != nil { fmt.Println(err) } else { fmt.Println(string(output)) } 지원하지 않는.. 2020. 3. 26.
[#golang] go modules로 쉽게 의존성 패키지 관리하기 module main go 1.13 require github.com/labstack/echo/v4 v4.1.15 // indirect golang에서 외부 패키지를 사용할때 보통 go get -u github.com/xxxxx 로 패키지를 다운받고 사용하고 싶은 .go 파일에서 import gitgub.com/xxxxx 로 임포트해서 사용한다. 근데 이런 경우, github.com/xxxxx 패키지가 업데이트된 후 go get -u github.com/xxxxx 을 하면 업데이트 이후 버전의 패키지를 다운받게되어 이전과 동작이 다르게 된다. 그래서 동일한, 혹은 특정한 패키지 버전을 보장할 수 있도록, 패키지 버저닝(Packaging Versionging) golang 11 버전에서 공식으로 도입된 G.. 2020. 3. 24.