golang中的http server和http client

一、golang http server

python中创建一个web服务器有python -m http.server
golang中创建一个web服务器很简单。
golang中有一个叫做http的包,已经封装好了,我们接下来简单介绍下net/http包的使用。使用go 的net/http包创建一个web服务器。性能怎么样呢?或者说golang的http是如何处理并发的?

导入依赖

import “net/http”

创建一个基础的http服务器

访问一个地址,映射到一个处理函数。

package main
 
import (
    "fmt"
    "net/http"
)
 
func main() {
        // handle route using handler function
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Welcome to new server!")
    })
 
        // listen to port
    http.ListenAndServe(":5050", nil)
}

处理多个路由

其实就是多加几个HandleFunc

package main
 
import (
    "fmt"
    "net/http"
)
 
func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Welcome to new server!")
    })
 
    http.HandleFunc("/students", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Welcome Students!")
    })
 
    http.HandleFunc("/teachers", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Welcome teachers!")
    })
 
    http.ListenAndServe(":5050", nil)
}

NewServeMux

NewServeMux是什么
NewServeMux vs DefaultServeMux

package main
 
import (
    "io"
    "net/http"
)
 
func welcome(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Welcome!")
}
 
func main() {
 
    mux := http.NewServeMux()
 
    mux.HandleFunc("/welcome", welcome)
 
    http.ListenAndServe(":5050", mux)
}

二、golang http client

如果不会写也没有关系,使用postman generate golang code,快速生成代码。

http.Get

// Get is a wrapper around DefaultClient.Get.

func Get(url string) (resp *Response, err error) {
return DefaultClient.Get(url)
}

下图中(c *Client) 这一部分不太理解啊。其实是指针接收者的概念了。
在这里插入图片描述


golang tips
一下子就把golang中的&和* 学会了,很好。

1、go 返回值可以返回多个值,需要使用小括号括起来。
2、go里面*是什么意思? 解引用,获得地址指向的值。将星号放在类型前面表示要声明指针类型,而将星号放在变量前面则表示解引用变量指向的值。
3、go里面&是什么意思? 和c语言很相似,获取内存地址使用&符号,例如

//叶常落伪代码
test := "this is test"
&test
address := &test
fmt.Print(*address)  
// 声明一个指针,这个指针只能只想string类型
var pointer *string

参考:
https://zhuanlan.zhihu.com/p/127940853 Go语言才是学习指针的安全之地,关于指针的二三事
https://zhuanlan.zhihu.com/p/338144672 Go 中的请求处理概述
https://golangdocs.com/http-server-in-golang

posted @ 2022-03-06 10:37  叶常落  阅读(122)  评论(0编辑  收藏  举报