zoukankan      html  css  js  c++  java
  • 7.6 request form post

    
    package main
    
    import (
    	"fmt"
    	"io/ioutil"
    	"net/http"
    	"net/url"
    	"strings"
    )
    
    type StringServer string
    
    func (s StringServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
    	req.ParseForm()
    	fmt.Printf("Received form data: %v
    ", req.Form)
    	fmt.Printf("Received header: %v
    ", req.Header)
    	rw.Write([]byte(string(s)))
    }
    
    func createServer(addr string) http.Server {
    	return http.Server{
    		Addr:    addr,
    		Handler: StringServer("Hello world"),
    	}
    }
    
    const addr = "localhost:7070"
    
    func main() {
    	s := createServer(addr)
    	go s.ListenAndServe()
    
    	form := url.Values{}
    	form.Set("id", "5")
    	form.Set("name", "Wolfgang")
    
    	req, err := http.NewRequest(http.MethodPost,
    		"http://localhost:7070",
    		strings.NewReader(form.Encode()))
    
    	if err != nil {
    		panic(err)
    	}
    	req.Header.Set("Content-Type",
    		"application/x-www-form-urlencoded")
    
    	res, err := http.DefaultClient.Do(req)
    	if err != nil {
    		panic(err)
    	}
    	data, err := ioutil.ReadAll(res.Body)
    	if err != nil {
    		panic(err)
    	}
    	res.Body.Close()
    	fmt.Println("Response from server:" + string(data))
    
    }
    
    /*
    Received form data: map[id:[5] name:[Wolfgang]]
    Received header: map[User-Agent:[Go-http-client/1.1] Content-Length:[18] Content-Type:[application/x-www-form-urlencoded] Accept-Encoding:[gzip]]
    Response from server:Hello world
    
    */
    
    
  • 相关阅读:
    .NET Tools...
    函数重载
    友元课后题
    怎么防止用户输入错误信息
    C#动态求圆的面积
    重载自增
    C++数学应用
    位运算符
    MSDN放出了VS2010简体中文正式版(附下载地址)
    字符串复制
  • 原文地址:https://www.cnblogs.com/zrdpy/p/8635857.html
Copyright © 2011-2022 走看看