'Programming'에 해당되는 글 1767건

  1. 2022.09.15 golang main arg, getopt
  2. 2022.09.15 golang json
  3. 2022.09.15 golang ini
  4. 2022.09.14 golang http.request
  5. 2022.09.06 golang range
  6. 2022.09.06 golang mutex
  7. 2022.09.06 golang make와 new
  8. 2022.09.06 golang defer 와 panic(), recover()
  9. 2022.09.06 go 루틴
  10. 2022.09.05 golang https server
Programming/golang2022. 9. 15. 19:00

 

package main

import (
	"fmt"
	"os"
)

func main() {
	argsWithProg := os.Args
	argsWithoutProg := os.Args[1:]

	// You can get individual args with normal indexing.
	arg := os.Args[3]

	fmt.Println(argsWithProg)
	fmt.Println(argsWithoutProg)
	fmt.Println(arg)
}

[링크 : https://gobyexample.com/command-line-arguments]

[링크 : https://stackoverflow.com/questions/2707434/how-to-access-command-line-arguments-passed-to-a-go-program]

[링크 : https://golangdocs.com/command-line-arguments-in-golang]

 

[링크 : https://pkg.go.dev/github.com/pborman/getopt]

 

[링크 : https://pkg.go.dev/os]

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

golang REST client  (0) 2022.09.23
golang 'go doc'  (0) 2022.09.15
golang json  (0) 2022.09.15
golang ini  (0) 2022.09.15
golang http.request  (0) 2022.09.14
Posted by 구차니
Programming/golang2022. 9. 15. 10:36

프로그램 환경설정 파일로 ini나 다른걸 찾아보는데

golang 기본 라이브러리로 json이 있고 yaml은 없다고 하니 고민중

 

func LoadConfigration(path string) Config {
    var config Config
    file, err := os.Open("config.json")
    defer file.Close()
    if err != nil {
        fmt.Println(err.Error())
    }
    jsonParser := json.NewDecoder(file)
    jsonParser.Decode(&config)
    return config
}

[링크 : https://loperlee.tistory.com/15]

 

import "encoding/json"

[링크 : https://pkg.go.dev/encoding/json]

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

golang 'go doc'  (0) 2022.09.15
golang main arg, getopt  (0) 2022.09.15
golang ini  (0) 2022.09.15
golang http.request  (0) 2022.09.14
golang range  (0) 2022.09.06
Posted by 구차니
Programming/golang2022. 9. 15. 10:34

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

golang main arg, getopt  (0) 2022.09.15
golang json  (0) 2022.09.15
golang http.request  (0) 2022.09.14
golang range  (0) 2022.09.06
golang mutex  (0) 2022.09.06
Posted by 구차니
Programming/golang2022. 9. 14. 16:26

ajax를 통해 DELETE type으로 변수를 넘겨줄 수 있나 찾아보는데

정작 보낸다고 해도 어떻게 golang에서 받아서 쓸 수 있나, r.ParseForm() 같은거 있나 찾아보는데 영 안보인다.

 

오랫만에 jquery  보니 ajax로 어떻게 DELETE를 보내더라? 기억도 잘 안나고 ㅠㅠ

[링크 : https://api.jquery.com/jQuery.ajax/#options]

 

부랴부랴 뒤져서 http.Request의 원형(?)을 찾았는데, Body와 GetBody() 발견

type Request struct {
Method string
URL *url.URL
Proto      string // "HTTP/1.0"
ProtoMajor int    // 1
ProtoMinor int    // 0
Header Header
Body io.ReadCloser
GetBody func() (io.ReadCloser, error)
ContentLength int64
TransferEncoding []string
Close bool
Host string
Form url.Values
PostForm url.Values
MultipartForm *multipart.Form
Trailer Header
RemoteAddr string
RequestURI string
TLS *tls.ConnectionState
Cancel <-chan struct{}
Response *Response
}

[링크 : https://pkg.go.dev/net/http#Request]

[링크 : https://www.digitalocean.com/community/tutorials/how-to-make-http-requests-in-go]

 

요거 되긴 한다. body에 json 담아 보내면 이렇게 읽으면 되는 듯

다만 "io/ioutil" 패키지를 추가해주어야 한다.

b, err := ioutil.ReadAll(req.Body)
if err != nil {
    panic(err)
}

fmt.Printf("%s", b)

[링크 : https://stackoverflow.com/questions/46579429/golang-cant-get-body-from-request-getbody]

[링크 : https://stackoverflow.com/questions/33164564/golang-parse-post-request]

 

$.ajax({
    url: '/v1/object/3.json',
    method: 'DELETE',
    contentType: 'application/json',
    success: function(result) {
        // handle success
    },
    error: function(request,msg,error) {
        // handle failure
    }
});

[링크 : https://stackoverflow.com/questions/2153917/how-to-send-a-put-delete-request-in-jquery]

[링크 : https://stackoverflow.com/questions/15088955/how-to-pass-data-in-the-ajax-delete-request-other-than-headers]

 

걍 속편하게 mux 쓰는게 나으려나?

[링크 : https://github.com/gorilla/mux]

  [링크 : https://morioh.com/p/9a0e53da7908]

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

golang json  (0) 2022.09.15
golang ini  (0) 2022.09.15
golang range  (0) 2022.09.06
golang mutex  (0) 2022.09.06
golang make와 new  (0) 2022.09.06
Posted by 구차니
Programming/golang2022. 9. 6. 17:03

일종의.. foreach 느낌인데

range pow 하면 pow에 들은 {1,2,4,8,16,32,64,128} 이 array index와 함께 i,v 값으로 나온다.

 

2**0=1 이렇게 해놔서 무슨 수식인줄 알았네 -_-

package main

import "fmt"

var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}

func main() {
for i, v := range pow {
fmt.Printf("2**%d = %d\n", i, v)
}
}
2**0 = 1
2**1 = 2
2**2 = 4
2**3 = 8
2**4 = 16
2**5 = 32
2**6 = 64
2**7 = 128

[링크 : https://go.dev/tour/moretypes/16]

 

[링크 : https://changhoi.kim/posts/go/about-go-range/]

[링크 : https://pronist.dev/88]

[링크 : https://gobyexample.com/range]

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

golang ini  (0) 2022.09.15
golang http.request  (0) 2022.09.14
golang mutex  (0) 2022.09.06
golang make와 new  (0) 2022.09.06
golang defer 와 panic(), recover()  (0) 2022.09.06
Posted by 구차니
Programming/golang2022. 9. 6. 16:54

세마포어는 있는지 모르겠다만 mutex는 존재하네

 

package main

import (
"fmt"
"sync"
"time"
)

// SafeCounter is safe to use concurrently.
type SafeCounter struct {
mu sync.Mutex
v  map[string]int
}

// Inc increments the counter for the given key.
func (c *SafeCounter) Inc(key string) {
c.mu.Lock()
// Lock so only one goroutine at a time can access the map c.v.
c.v[key]++
c.mu.Unlock()
}

// Value returns the current value of the counter for the given key.
func (c *SafeCounter) Value(key string) int {
c.mu.Lock()
// Lock so only one goroutine at a time can access the map c.v.
defer c.mu.Unlock()
return c.v[key]
}

[링크 : https://go.dev/tour/concurrency/9]

 

관련 검색어로 golang mutex vs channel 이라는게 나오는데 channel이 그렇게 빠르지는 않은 듯.

[링크 : http://www.dogfootlife.com/archives/452]

[링크 : https://github.com/golang/go/wiki/MutexOrChannel]

[링크 : https://go.dev/doc/effective_go#channels]

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

golang http.request  (0) 2022.09.14
golang range  (0) 2022.09.06
golang make와 new  (0) 2022.09.06
golang defer 와 panic(), recover()  (0) 2022.09.06
go 루틴  (0) 2022.09.06
Posted by 구차니
Programming/golang2022. 9. 6. 15:27

new는 c의 malloc()에 대응한다면

make는 특정 경우에 대한 메모리 할당 + 초기화를 위한 키워드인 듯.

package main

import "fmt"

func sum(s []int, c chan int) {
sum := 0
for _, v := range s {
sum += v
}
c <- sum // send sum to c
}

func main() {
s := []int{7, 2, 8, -9, 4, 0}

c := make(chan int)
go sum(s[:len(s)/2], c)
go sum(s[len(s)/2:], c)
x, y := <-c, <-c // receive from c

fmt.Println(x, y, x+y)
}

[링크 : https://go.dev/tour/concurrency/2]

 

Allocation with new
Go has two allocation primitives, the built-in functions new and make. They do different things and apply to different types, which can be confusing, but the rules are simple. Let's talk about new first. It's a built-in function that allocates memory, but unlike its namesakes in some other languages it does not initialize the memory, it only zeros it. That is, new(T) allocates zeroed storage for a new item of type T and returns its address, a value of type *T. In Go terminology, it returns a pointer to a newly allocated zero value of type T.
Since the memory returned by new is zeroed, it's helpful to arrange when designing your data structures that the zero value of each type can be used without further initialization. This means a user of the data structure can create one with new and get right to work. For example, the documentation for bytes.Buffer states that "the zero value for Buffer is an empty buffer ready to use." Similarly, sync.Mutex does not have an explicit constructor or Init method. Instead, the zero value for a sync.Mutex is defined to be an unlocked mutex.

[링크 : https://go.dev/doc/effective_go#allocation_new]

 

Allocation with make
Back to allocation. The built-in function make(T, args) serves a purpose different from new(T). It creates slices, maps, and channels only, and it returns an initialized (not zeroed) value of type T (not *T). 

[링크 : https://go.dev/doc/effective_go#allocation_make]

[링크 : https://pronist.dev/102]

 

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

golang range  (0) 2022.09.06
golang mutex  (0) 2022.09.06
golang defer 와 panic(), recover()  (0) 2022.09.06
go 루틴  (0) 2022.09.06
golang https server  (0) 2022.09.05
Posted by 구차니
Programming/golang2022. 9. 6. 15:13

panic은 c로 치면 exit()도, recover()는 return 정도라고 보면 되려나?

package main
 
import "os"
 
func main() {
    // 잘못된 파일명을 넣음
    openFile("Invalid.txt")
     
    // openFile() 안에서 panic이 실행되면
    // 아래 println 문장은 실행 안됨
    println("Done") 
}
 
func openFile(fn string) {
    f, err := os.Open(fn)
    if err != nil {
        panic(err)
    }
 
    defer f.Close()
}










package main
 
import (
    "fmt"
    "os"
)
 
func main() {
    // 잘못된 파일명을 넣음
    openFile("Invalid.txt")
 
    // recover에 의해
    // 이 문장 실행됨
    println("Done") 
}
 
func openFile(fn string) {
    // defer 함수. panic 호출시 실행됨
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("OPEN ERROR", r)
        }
    }()
 
    f, err := os.Open(fn)
    if err != nil {
        panic(err)
    }
 
    defer f.Close()
}
$ ./panic
panic: open Invalid.txt: no such file or directory

goroutine 1 [running]:
main.openFile({0x8b9f9, 0xb})
        /home/pi/panic.go:17 +0xb4
main.main()
        /home/pi/panic.go:7 +0x24
$ ./recover
OPEN ERROR open Invalid.txt: no such file or directory
Done





[링크 : http://golang.site/go/article/20-Go-defer와-panic]

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

golang mutex  (0) 2022.09.06
golang make와 new  (0) 2022.09.06
go 루틴  (0) 2022.09.06
golang https server  (0) 2022.09.05
golang 쿠키  (0) 2022.09.02
Posted by 구차니
Programming/golang2022. 9. 6. 12:48

go 루틴은 쓰레드로 작동시킨다.

 

go funcname()

[링크 : http://golang.site/go/article/21-Go-루틴-goroutine]

 

왜.. 생소하지 -ㅁ-?

package main

import (
"fmt"
"time"
)

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")
}

[링크 : https://go.dev/tour/concurrency/1]

 

고루틴은 parent에 의해서 죽일수 없다고 하는데

[링크 : https://www.reddit.com/r/golang/comments/4kpv6x/why_a_parent_goroutine_doesnt_kill_its_child_and/]

 

그래서 channel을 이용해서 해당 채널을 close 하면 닫는 식으로 간접 제어 하기도 하는 듯

package main

import (
"fmt"
"sync"
)

func main() {
var wg sync.WaitGroup
wg.Add(1)

ch := make(chan string)
go func() {
for {
channel, ok := <-ch
if !ok {
fmt.Println("Shut Down")
defer wg.Done()
return
}
fmt.Println(channel)
}
}()
ch <- "Start"
ch <- "Processing"
ch <- "Finishing"
close(ch)

wg.Wait()
}


[링크 :
https://www.golangprograms.com/how-to-kill-execution-of-goroutine.html]

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

golang make와 new  (0) 2022.09.06
golang defer 와 panic(), recover()  (0) 2022.09.06
golang https server  (0) 2022.09.05
golang 쿠키  (0) 2022.09.02
golang http redirect  (0) 2022.09.02
Posted by 구차니
Programming/golang2022. 9. 5. 13:47

http 서버는 쉽게 돌렸는데, https로 어떻게 돌리나 검색.

그런데 인증서 제작과정이 더 번거로운게 함정..(그게 아니면 Let's encrypt 이런거 써야하나..)

[링크 :https://dksshddl.tistory.com/entry/GO-https-제공을-위한-인증된-SSL과-서버-개인-키-생성하기]

 

http.ListenAndServe()를 사용했는데

두개 인자(cert, key)를 더 넣어주고 TLS만 붙이면 끝!

func ListenAndServe(addr string, handler Handler) error
func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error

 

아무생각없이 했더니 :443으로 해주면 1024 포트 이하라 root 권한 필요하니 주의

package main

import (
"io"
"log"
"net/http"
)

func main() {
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "Hello, TLS!\n")
})

// One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
log.Printf("About to listen on 8443. Go to https://127.0.0.1:8443/")
err := http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil)
log.Fatal(err)
}

[링크 : https://pkg.go.dev/net/http#ListenAndServe]

[링크 : https://pkg.go.dev/net/http#ListenAndServeTLS]

 

귀찮으니 한번에 대충 따라해서 생성

openssl genrsa -out server.key 2048
openssl req -new -key server.key -out server.csr
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
openssl rsa -in server.key -text > key.pem
openssl x509 -inform PEM -in server.crt -text > cert.pem

[링크 : https://0netw0m1ra.tistory.com/187]

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

golang defer 와 panic(), recover()  (0) 2022.09.06
go 루틴  (0) 2022.09.06
golang 쿠키  (0) 2022.09.02
golang http redirect  (0) 2022.09.02
golang html form post 처리하기  (0) 2022.09.02
Posted by 구차니