Go的学习旅程9:Http,Web,websocket的简单实现

xiaoxiao2021-03-01  4

    golang的web运行效率还是和nginx相同,而且实现起来还是很简单的;

    简单的调用:

server

package main import ( "net/http" "fmt" ) func hello(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello,世界!!") } func login(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "请登陆!!!!") } func main() { http.HandleFunc("/", hello) http.HandleFunc("/login", login) //监听本机的8080端口 http.ListenAndServe(":8080", nil) }

    测试:

            

server-获取参数

     一、获取GET参数

package main import ( "net/http" "fmt" ) func hello(w http.ResponseWriter, r *http.Request) { //ParseForm解析URL中的查询字符串,并将解析结果更新到r.Form字段。 r.ParseForm() if len(r.Form["id"]) > 0 { fmt.Fprintln(w, r.Form["id"][0]) } if len(r.Form.Get("id")) > 0 { fmt.Fprintln(w, r.Form.Get("id")) } } func main() { http.HandleFunc("/", hello) http.ListenAndServe(":8080", nil) }

    二、获取POST参数

    2.1 获取单个POST字段值

package main import ( "net/http" "fmt" ) func hello(w http.ResponseWriter, r *http.Request) { id := r.PostFormValue("id") fmt.Fprintln(w,id) } func main() { http.HandleFunc("/", hello) http.ListenAndServe(":8080", nil) }

    2.2 获取多个POST字段值

package main import ( "net/http" "fmt" ) func hello(w http.ResponseWriter, r *http.Request) { id := r.PostForm["id"] fmt.Fprintln(w,id) } func main() { http.HandleFunc("/", hello) http.ListenAndServe(":8080", nil) }

    

    client-get

package main import ( "net/http" "io/ioutil" "fmt" ) func main() { resp, err := http.Get("https://www.baidu.com/") if err != nil { panic(err) } data,err:=ioutil.ReadAll(resp.Body) fmt.Println(string(data)) }

    

    client-Post1

package main import ( "io/ioutil" "fmt" "strconv" "net/http" "strings" ) func main() { id := "brandId=" + strconv.Itoa(33) resp, err := http.Post("https://j.autohome.com.cn/pcplatform/common/getSeriesInfo", "application/x-www-form-urlencoded", strings.NewReader(id)) defer resp.Body.Close() if err != nil { panic(err) } data, err := ioutil.ReadAll(resp.Body) fmt.Println(string(data)) }

    client-Post2

package main import ( "io/ioutil" "fmt" "net/http" "net/url" ) func main() { resp, err := http.PostForm("https://j.autohome.com.cn/pcplatform/common/getSeriesInfo", url.Values{"brandId":{"33"}}) defer resp.Body.Close() if err != nil { panic(err) } data, err := ioutil.ReadAll(resp.Body) fmt.Println(string(data)) }

client这几种访问方式中,封装的很简单,而且效率也很不错,做为爬虫的第一语言还是不错的(golang一分钟上万条数据,而且还是没有开协程的情况下,不要和我说python,慢的一笔);

好的,现在说websocket,实现起来比较的简单,

直接上码

server.go

package main import ( "fmt" "golang.org/x/net/websocket" "net/http" "log" "time" ) func Echo(ws *websocket.Conn) { var err error for { var Msg string //接收消息 if err = websocket.Message.Receive(ws, &Msg); err != nil { fmt.Println("接收失败") break } fmt.Println("来自客户端的消息: " + Msg) //传递消息 if err = websocket.Message.Send(ws, "现在时间是:"+time.Now().Format("2006-01-02 15:04:05")); err != nil { fmt.Println("Can't send") break } } } func main() { fmt.Println("Start app") http.Handle("/", websocket.Handler(Echo)) if err := http.ListenAndServe(":8000", nil); err != nil { log.Fatal("ListenAndServe:", err) } }

Index.html

<html> <head></head> <body> <script type="text/javascript"> var sock = null; var wsuri = "ws://127.0.0.1:8000"; window.onload = function() { console.log("onload"); sock = new WebSocket(wsuri); sock.onopen = function() { console.log("connected to " + wsuri); } sock.onclose = function(e) { console.log("connection closed (" + e.code + ")"); } sock.onmessage = function(e) { console.log("message received: " + e.data); } }; function send() { var msg = document.getElementById('message').value; sock.send(msg); } </script> <h1>WebSocket Echo Test</h1> <form> <p>Message: <input id="message" type="text" value="Hello, world!"></p> </form> <button οnclick="send();">Send Message</button> </body> </html>
转载请注明原文地址: https://www.6miu.com/read-3849986.html

最新回复(0)