'Programming/golang'에 해당되는 글 110건

  1. 2022.09.02 golang http redirect
  2. 2022.09.02 golang html form post 처리하기
  3. 2022.08.31 golang http.HandleFunc(pattern)
  4. 2022.08.30 golang mariadb 연동
  5. 2022.08.18 golang channel
  6. 2022.07.20 golang unused import
  7. 2022.07.15 golang websocket package
  8. 2022.04.18 go run ./ 2
  9. 2022.04.13 golang module
  10. 2022.04.11 golang 구조체
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 구차니
Programming/golang2022. 8. 31. 18:00

golang을 이용해서 rest 서버를 만드는데 가장 만만한(?) 녀석은

net/http 모듈의 http.HandleFunc() 인데

 

pattern 이라고 써넣고는 막상 설명이 없다.

func HandleFunc(pattern string, handler func(ResponseWriter, *Request))

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

 

음.. 소스를 봐도 모르겠다.

// Handle registers the handler for the given pattern.
// If a handler already exists for pattern, Handle panics.
func (mux *ServeMux) Handle(pattern string, handler Handler) {
mux.mu.Lock()
defer mux.mu.Unlock()

if pattern == "" {
panic("http: invalid pattern")
}
if handler == nil {
panic("http: nil handler")
}
if _, exist := mux.m[pattern]; exist {
panic("http: multiple registrations for " + pattern)
}

if mux.m == nil {
mux.m = make(map[string]muxEntry)
}
e := muxEntry{h: handler, pattern: pattern}
mux.m[pattern] = e
if pattern[len(pattern)-1] == '/' {
mux.es = appendSorted(mux.es, e)
}

if pattern[0] != '/' {
mux.hosts = true
}
}

[링크 : https://cs.opensource.google/go/go/+/refs/tags/go1.19:src/net/http/server.go;drc=ddc93a536faf4576d182cd3197b116d61d05c484;l=2480]

 

걍.. gin 모듈을 쓰는게 속 편하려나?

[링크 : https://stackoverflow.com/questions/6564558/wildcards-in-the-pattern-for-http-handlefunc]

 

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

golang http redirect  (0) 2022.09.02
golang html form post 처리하기  (0) 2022.09.02
golang mariadb 연동  (0) 2022.08.30
golang channel  (0) 2022.08.18
golang unused import  (0) 2022.07.20
Posted by 구차니
Programming/golang2022. 8. 30. 12:31

테스트 해보니

localhost:3306 접속시에는 username:password@/dbname 식으로 접속해도 된다.

 

db, _ := sql.Open("mysql", "dellis:@/shud")

[링크 : https://mariadb.com/ko/resources/blog/using-go-with-mariadb/]

[링크 : https://pkg.go.dev/database/sql]

 

db, err := sql.Open("mysql", "root:pwd@tcp(127.0.0.1:3306)/testdb")

[링크 : http://golang.site/go/article/107-MySql-사용---쿼리]

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

golang html form post 처리하기  (0) 2022.09.02
golang http.HandleFunc(pattern)  (0) 2022.08.31
golang channel  (0) 2022.08.18
golang unused import  (0) 2022.07.20
golang websocket package  (0) 2022.07.15
Posted by 구차니
Programming/golang2022. 8. 18. 12:18

<-

이런 연산자가 보여서 먼가 찾아보는 중

 

[링크 : https://etloveguitar.tistory.com/40]

[링크 : https://go.dev/ref/spec#Receive_operator]

[링크 : https://go.dev/ref/spec#Channel_types]

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

golang http.HandleFunc(pattern)  (0) 2022.08.31
golang mariadb 연동  (0) 2022.08.30
golang unused import  (0) 2022.07.20
golang websocket package  (0) 2022.07.15
go run ./  (2) 2022.04.18
Posted by 구차니
Programming/golang2022. 7. 20. 19:04

 

import (
"encoding/json"
"net/http"
"fmt"
"io"

"github.com/go-resty/resty/v2"
"golang.org/x/net/websocket"
)
./main.go:9:2: imported and not used: "github.com/go-resty/resty/v2" as resty

 

밑줄(_) 하나 넣어주면 넘어가긴 한다.

다만, 사용시에는 _를 빼줘야 정상적으로 인식해서 넣으나 마나하니.. 걍 주석처리 하는게 귀찮아도 나을 지도..?

import (
"encoding/json"
"net/http"
"fmt"
"io"

_ "github.com/go-resty/resty/v2"
"golang.org/x/net/websocket"
)

[링크 : https://stackoverflow.com/questions/25924749/import-and-not-used-error]

[링크 : https://knight76.tistory.com/entry/golang-imported-and-not-used]

[링크 : https://go.dev/doc/faq#unused_variables_and_imports]

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

golang mariadb 연동  (0) 2022.08.30
golang channel  (0) 2022.08.18
golang websocket package  (0) 2022.07.15
go run ./  (2) 2022.04.18
golang module  (0) 2022.04.13
Posted by 구차니
Programming/golang2022. 7. 15. 19:07

아래처럼 넣어주면 끝.

 

package main

import (
"fmt"
"log"

"golang.org/x/net/websocket"
)

func main() {
origin := "http://localhost/"
url := "ws://localhost:12345/ws"
ws, err := websocket.Dial(url, "", origin)
if err != nil {
log.Fatal(err)
}
if _, err := ws.Write([]byte("hello, world!\n")); err != nil {
log.Fatal(err)
}
var msg = make([]byte, 512)
var n int
if n, err = ws.Read(msg); err != nil {
log.Fatal(err)
}
fmt.Printf("Received: %s.\n", msg[:n])
}

[링크 : https://pkg.go.dev/golang.org/x/net/websocket]

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

golang channel  (0) 2022.08.18
golang unused import  (0) 2022.07.20
go run ./  (2) 2022.04.18
golang module  (0) 2022.04.13
golang 구조체  (0) 2022.04.11
Posted by 구차니
Programming/golang2022. 4. 18. 19:15

 

$ cat hello.go 
package main

import "fmt"

func main() {
fmt.Println("Hello world")
hello()
}

$ cat func.go 
package main

import "fmt"

func hello() {
fmt.Println("Hello world 2")
}

$ go run .
go: go.mod file not found in current directory or any parent directory; see 'go help modules'

$ go mod init
go: creating new go.mod: module go2
go: to add module requirements and sums:
go mod tidy

$ go run .
Hello world
Hello world 2

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

golang unused import  (0) 2022.07.20
golang websocket package  (0) 2022.07.15
golang module  (0) 2022.04.13
golang 구조체  (0) 2022.04.11
golang defer와 if  (0) 2022.04.11
Posted by 구차니
Programming/golang2022. 4. 13. 10:11

C언어 처럼 단순(?)한게 아니라 자바의 패키지 처럼

모듈로 만들어야 끌어올 수 있다고 한다.

 

[링크 : https://tutorialedge.net/golang/go-modules-tutorial/]

[링크 : https://www.digitalocean.com/community/tutorials/how-to-use-go-modules]

 

[링크 : https://velog.io/@comdori-web/Go-package와-module]

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

golang websocket package  (0) 2022.07.15
go run ./  (2) 2022.04.18
golang 구조체  (0) 2022.04.11
golang defer와 if  (0) 2022.04.11
golang a tour of go offline  (0) 2022.04.07
Posted by 구차니
Programming/golang2022. 4. 11. 16:27

변수타입이 뒤로 가는 걸 제외하면 문법은 그대로~

 

package main

import "fmt"

type Vertex struct {
X int
Y int
}

func main() {
v := Vertex{1, 2}
v.X = 4
fmt.Println(v.X)
}

[링크 : https://go-tour-ko.appspot.com/moretypes/3]

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

go run ./  (2) 2022.04.18
golang module  (0) 2022.04.13
golang defer와 if  (0) 2022.04.11
golang a tour of go offline  (0) 2022.04.07
golang struct  (0) 2022.04.07
Posted by 구차니