'Programming'에 해당되는 글 1762건

  1. 2022.09.06 golang range
  2. 2022.09.06 golang mutex
  3. 2022.09.06 golang make와 new
  4. 2022.09.06 golang defer 와 panic(), recover()
  5. 2022.09.06 go 루틴
  6. 2022.09.05 golang https server
  7. 2022.09.05 jquery-cookie 라이브러리
  8. 2022.09.02 golang 쿠키
  9. 2022.09.02 golang http redirect
  10. 2022.09.02 golang html form post 처리하기
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 구차니
Programming/jquery2022. 9. 5. 11:57

서버에서 request cookie로 보내면 document.cookie로 접근이 가능한데

그걸 간단하게 사용하기 위한 라이브러리

[링크 : https://hailey0.tistory.com/38]

 

 

function getCookie(cname) {
  let name = cname + "=";
  let decodedCookie = decodeURIComponent(document.cookie);
  let ca = decodedCookie.split(';');
  for(let i = 0; i <ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

[링크 : https://www.w3schools.com/js/js_cookies.asp]

 

[링크 : https://nowonbun.tistory.com/634]

 

그나저나  document.cookie가 왜이렇게 생소하지?

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

jquery ajax auth  (0) 2023.07.27
jquery ajax delete가 없다?  (0) 2022.09.16
jquery 우클릭 가로채기  (0) 2019.06.04
jquery ajax json flask  (0) 2019.01.07
jquery this 버튼 checked  (0) 2019.01.07
Posted by 구차니
Programming/golang2022. 9. 2. 16:44

 

func createCookie(w http.ResponseWriter, req *http.Request) { 
    http.SetCookie(w, &http.Cookie{
        Name: "name of cookie",
        Value: "value of cookie",
        Path: "/",
    })
}

func expireCookie(w http.ResponseWriter, req *http.Request) {
    cookie, err := r.Cookie("cookie-name")
    
    if err := nil{
    }
    // 1. 쿠키 삭제
    // cookie.MaxAge = -1
    
    // 2. 쿠키를 5초간 지속
    // cookie.MaxAge = 5
    
    // 3. expires 설정, 현재시간으로 부터 1시간 뒤 == 쿠키의 만료시각
    // expiration := time.Now().Add(time.Hour)
    // cookie.Expires = expiration
    
    http.SetCookie(w, cookie)
    http.Redirect(w, req, "/", http.StatusSeeOther)
}

[링크 : https://velog.io/@j1mmyson/golang-go언어에서의-쿠키-사용]

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

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

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

go 루틴  (0) 2022.09.06
golang https server  (0) 2022.09.05
golang http redirect  (0) 2022.09.02
golang html form post 처리하기  (0) 2022.09.02
golang http.HandleFunc(pattern)  (0) 2022.08.31
Posted by 구차니
Programming/golang2022. 9. 2. 16:29

form post 로 받아서 DB로 조회하고 성공시, 어떻게 다른 링크로 돌려보내나 고민을 했는데

http.Redirect()라는 함수를 발견. StatusSeeOther는 303 코드인데 좀.. 생소하네?

 

if r.Method == "POST" {
    saveChoice(r.Form["choices"])
    http.Redirect(w, r, newUrl, http.StatusSeeOther)
}

[링크 : https://stackoverflow.com/questions/35934298/how-to-redirect-to-a-url]

 

특이하게도.. Response와 Request 둘다 들어와야 쓸 수 있는 녀석.

func Redirect(w ResponseWriter, r *Request, url string, code int)
Redirect replies to the request with a redirect to url, which may be a path relative to the request path.

The provided code should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther.

If the Content-Type header has not been set, Redirect sets it to "text/html; charset=utf-8" and writes a small HTML body. Setting the Content-Type header to any value, including nil, disables that behavior.

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

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

golang https server  (0) 2022.09.05
golang 쿠키  (0) 2022.09.02
golang html form post 처리하기  (0) 2022.09.02
golang http.HandleFunc(pattern)  (0) 2022.08.31
golang mariadb 연동  (0) 2022.08.30
Posted by 구차니
Programming/golang2022. 9. 2. 15:31

오랫만에 HTML 하니 다 까먹었네..

html 에서는 아래와 같이 post로 넘겨줄 변수 명은 name에 기재하고 form method를 post로 해주면 끝!

다만 action은 생략될 수 있으므로 처리해야할 페이지의 링크를 기록해주면 된다.

<form method="post" action="url">
<intut type="text" name="username">
</form>

 

func loginHandler(wr http.ResponseWriter, r *http.Request) {
        r.ParseForm()
        switch r.Method {
                case http.MethodPost: // 조회
                        fmt.Println(r)
                        fmt.Println(r.Form)
                        fmt.Println(r.PostForm)
                        fmt.Fprintln(wr, r.Form)
        }
}

[링크 : https://dksshddl.tistory.com/entry/Go-web-programming-request-처리-및-response-작성]

 

ParseForm() 을 실행하지 않으면, r.Form이 업데이트 되지 않아 내용이 조회가 되지 않는다.

ParseForm populates r.Form and r.PostForm.

For all requests, ParseForm parses the raw query from the URL and updates r.Form.

For POST, PUT, and PATCH requests, it also reads the request body, parses it as a form and puts the results into both r.PostForm and r.Form. Request body parameters take precedence over URL query string values in r.Form.

If the request Body's size has not already been limited by MaxBytesReader, the size is capped at 10MB.

For other HTTP methods, or when the Content-Type is not application/x-www-form-urlencoded, the request Body is not read, and r.PostForm is initialized to a non-nil, empty value.

ParseMultipartForm calls ParseForm automatically. ParseForm is idempotent.

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

 

html post를 직접 하는건데 유용한(?) 라이브러리가 보여서 링크!

import "encoding/json"
import "encoding/xml"

[링크 : http://golang.site/go/article/103-HTTP-POST-호출]

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

golang 쿠키  (0) 2022.09.02
golang http redirect  (0) 2022.09.02
golang http.HandleFunc(pattern)  (0) 2022.08.31
golang mariadb 연동  (0) 2022.08.30
golang channel  (0) 2022.08.18
Posted by 구차니