时间:2023-05-29 07:36:01 | 来源:网站运营
时间:2023-05-29 07:36:01 来源:网站运营
Go Web编程实战(8)----创建HTTP与HTTPS服务器端:package mainimport ( "fmt" "net/http")func helloworld(w http.ResponseWriter,r *http.Request) { fmt.Fprintf(w,"Hello World")}func main() { server :=&http.Server{ Addr: "127.0.0.1:80", } http.HandleFunc("/",helloworld) server.ListenAndServe()}
运行之后,在浏览器的网页输入框中输入127.0.0.1就会出现“Hello World”的简单网页。type Handler interface{ ServerHTTP(ResponseWriter,*Request)}
只要实现了这个接口,就可以实现自己的handler处理器。其具体的实现方式如下:type HandlerFunc func(ResponseWriter,*Request)func (f HandlerFunc)ServerHTTP(w ResponseWriter,r *Request){ f(w,r)}
handler处理器类似于Java SpringMVC框架中的Interceptor,是一个拦截器。它发生在http.HandlerFunc()函数处理逻辑之前。type Refer struct { handler http.Handler refer string}
这里可以看到,作者定义了2个对象,handler与自定义的refer。package mainimport ( "fmt" "net/http")type Refer struct { handler http.Handler refer string}func (this *Refer) ServeHTTP(w http.ResponseWriter,r *http.Request) { if r.Referer()==this.refer{ this.handler.ServeHTTP(w,r) }else{ w.WriteHeader(403) }}func myHandler(w http.ResponseWriter,r *http.Request) { w.Write([]byte("这是handler"))}func helloworld(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World")}func main() { referer :=&Refer{ handler: http.HandlerFunc(myHandler), refer: "www.liyuanjing.com", } http.HandleFunc("/hello", helloworld) http.ListenAndServe(":80",referer)}
这个时候,如果运行后,你直接输入127.0.0.1,网页会显示拒绝访问。func (srv *Server)ListenAndServeTLS(certFile,keyFile string) error
通过上面的方法,我们可以知道,HTTPS服务的创建只需要2个参数即可。其中,第一个参数为证书文件的路径,第二个参数为私钥文件的路径。openssl req -newkey rsa:2048 -nodes -keyout server.key -x509 -days 365 -out server.crt
执行该命令后,命令行的输出内容如下。这里,读者可以随便输入。package mainimport ( "net/http")func handle(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello World HTTPS"))}func main() { server := &http.Server{Addr: ":80", Handler: http.HandlerFunc(handle)} server.ListenAndServeTLS("server.crt", "server.key")}
运行之后,网页不会输出Hello World HTTPS,那是因为这么创建的HTTPS相关证书是不被互联网认可的,但创建的过程就是这样。关键词:服务,创建,实战