golang기초-http 요청의 몇 가지 방식
3594 단어 Go 베이스
문서 목록
get 요청 보내기
func main() {
http.HandleFunc("/test1",test1)
http.HandleFunc("/t_test1",t_test1)
http.ListenAndServe("0.0.0.0:9999",nil)
}
func t_test1(res http.ResponseWriter,req *http.Request) {
// URL
sendUrl,_:=url.Parse("http://localhost:9999/test1?")
// Values
val:=sendUrl.Query()
val.Set("name","safly")
val.Add("name","saflyer")
val.Set("sex","man")
// RawQuery
sendUrl.RawQuery = val.Encode()
//
resp,err:=http.Get(sendUrl.String())
if err != nil || resp.StatusCode != http.StatusOK{
fmt.Println("get fail:", err)
return
}
defer resp.Body.Close()
//
body,err:=ioutil.ReadAll(resp.Body)
if err!= nil{
fmt.Println("read body fail")
return
}
fmt.Println(string(body))
}
func test1(res http.ResponseWriter,req *http.Request) {
req.ParseForm()
for k,v:=range req.Form{
fmt.Print(k,v)
}
fmt.Fprint(res, "It works")
}
curl -X GET 'http://localhost:9999/t_test1'
요청 테스트를 수행하여 출력은 다음과 같습니다.name[safly saflyer]sex[man]It works
포스터를 해석하는 방식으로 json 대상을 해석합니다
func main() {
http.HandleFunc("/post",post)
http.HandleFunc("/t_post",t_post)
http.ListenAndServe("0.0.0.0:9999",nil)
}
func t_post(res http.ResponseWriter,req *http.Request) {
// URL
sendUrl:="http://localhost:9999/post?"
user:= struct {
Name string
Sex string
}{"safly","man"}
body,_:=json.Marshal(user)
resp,_:= http.Post(sendUrl,"application/x-www-form-urlencoded",strings.NewReader(string(body)))
//
defer resp.Body.Close()
b,_:= ioutil.ReadAll(resp.Body)
fmt.Println(string(b))
}
func post(res http.ResponseWriter,req *http.Request) {
// body
body,_:= ioutil.ReadAll(req.Body)
strBody:= string(body)
fmt.Println("bodyStr",strBody)
userT:= struct {
Name string
Sex string
}{}
json.Unmarshal(body,&userT)
fmt.Fprint(res,userT.Name,userT.Sex)
}
curl -X POST 'http://localhost:9999/t_post'
요청 테스트를 수행하여 출력은 다음과 같습니다.bodyStr {"Name":"safly","Sex":"man"}
saflyman
분석은 폼으로postform 데이터를 제출합니다
func main() {
http.HandleFunc("/post",post)
http.HandleFunc("/t_post",t_post)
http.ListenAndServe("0.0.0.0:9999",nil)
}
func post(w http.ResponseWriter,r *http.Request) {
r.ParseForm()
fmt.Println(r.Form["name"])
fmt.Println(r.Form["sex"])
//
fmt.Fprint(w, "Post is works")
}
func t_post(res http.ResponseWriter,req *http.Request) {
u, err := url.Parse("http://localhost:9999/post?")
if err != nil {
fmt.Println("parse is fail")
return
}
q := u.Query()
q.Set("name", "salfy")
q.Add("name","saflyer")
q.Set("sex", " ")
// post
resp, err1 := http.PostForm(u.String(), q)
if err1 != nil {
fmt.Println("post fail")
return
}
//
defer resp.Body.Close()
body, err2 := ioutil.ReadAll(resp.Body)
if err2 != nil{
fmt.Println("body fail")
return
}
fmt.Println(string(body))
}
curl -X POST 'http://localhost:9999/t_post'
요청 테스트를 수행하여 출력은 다음과 같습니다.[salfy saflyer]
[ ]
Post is works